0

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?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 2
    It's actually getchar that does this – user253751 Oct 16 '18 at 01:47
  • What makes you think the two calls to putchar act differently? Surely the whole line is printed when you press the ENTER key? – rici Oct 16 '18 at 02:16
  • Use braces in your code – Ed Heal Oct 16 '18 at 02:35
  • The `putchar` does follow the` getchar` very quickly, but the `getchar` is blocking until you hit the enter key because the tty is buffering the data for you. Once you hit enter, the tty sends the entire line to your program. If you want different behavior, you need to change the mode of the tty. – William Pursell Oct 16 '18 at 03:10

2 Answers2

2

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?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
-1

Output buffering. C library stdio has new line'd buffer has output buffering. TO disable buffering call setbuf(stdout, NULL);

Ryan
  • 14,392
  • 8
  • 62
  • 102