On Thu, 05 Feb 2004 18:42:01 +0530, Prem Mallappa
<pr***********@hotpop.com> wrote:
Hi everybody
here is my code to print all nonblank character on Input.. This program
according to my knowledge should run till i press Ctrl+D but,,, this is
parsing the input untill i press RETURN ( ENTER).. Why is it so..
thx in advance
prem mallappa
#include <stdio.h>
int main(void)
{
int c;
while ( ( c = getchar() ) != EOF)
{
if ( c == ' ' || c == '\t' || c == '\n')
;
else
putchar (c);
}
return 0;
}
It may help to understand the rationale for _why_ you need to press
return before it begins to respond:
Under Unix, where the model for this behavior was forged, the I/O
subsystems (often complete computers, or the equivalent thereof, in
their own right) are often separate from the CPU. To off-load the
burden of dealing with I/O from the CPU, your app (within the
machinations of the first getchar() call) will internally place a
system call that directs the I/O subsystem to "get a line". While this
is happening, perhaps reading from a disk, the CPU is free to work on
other tasks it would rather be doing (like giving time to other
computational processes).
Since the I/O processor doesn't understand the logic of your program,
it goes by simple rules: buffer up until we see a newline or EOF. BTW,
the reason typing ^D doesn't act as an EOF in your case is that it
appears in the middle of a line...it doesn't _count_ as an EOF that
way [don't shoot me, I'm just the messenger].
Once the I/O processor has buffered up its line, only _then_ will
getchar() return with the first character...and then each subsequent
call to getchar() until the line is exhausted won't require I/O,
because the data has already been cached up in memory.
Make sense?
-leor
Leor Zolman
BD Software
le**@bdsoft.com www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at
www.bdsoft.com/tools/stlfilt.html