Reputation: 22043
I am following the book "C Primer Plus" and encounter such a snippet of code:
#include <stdio.h>
#include <ctype.h>
#define SPACE ' '
int main(void) {
char ch = getchar();
while (ch != '\n')
{
if (isalpha(ch))
putchar(ch + 1); //change other characters
else
putchar(ch);
ch = getchar();
}
putchar(ch); //print the newline
return 0;
}
run it and output:
$ ./a.out
a c programmer
b d qsphsbnnfs
I assume when I input a
, it will immediately output b. However, it wait until I strike enter.
It seem that the second putchar(ch) works properly.
What's the reason putchar(n+1)
not put it char immediately as the second putchar(ch) did?
Upvotes: 0
Views: 461
Reputation: 153338
assume when I input a, it will immediately output b. However, it wait until I strike enter.
"a, ... immediately output b" --> not likely.
What's the reason putchar(n+1) not put it char immediately as the second putchar(ch) did?
Input buffering is the likely first concern as stdin
is often line buffered.
Typically nothing of the first characters of a line are even available to stdin
until Enter or '\n'
are entered (and echoed).
With line buffered input, the entire "a c programmer\n"
is keyed in and echoed before the first getchar()
call returns with 'a'
.
Aside from this common case, other possibilities exist as this is implementation defined.
Output buffering likely occurs too, but that is something after all the 1st line's input is entered and echoed. Thus when putchar('b'), putchar(' '), ...
execute, no output is seen until putchar('\n')
. See What are the rules of automatic flushing stdout buffer in C?
Upvotes: 2
Reputation: 14649
Output buffering. C library stdio has new line'd buffer has output buffering. TO disable buffering call setbuf(stdout, NULL);
Upvotes: -1