1

I'm new to C, sorry if this question is basic. I'm trying to understand the behaviour of the getchar() function.

Here I have two versions of my code:

The first one:

#include <stdio.h>

int main()
{
    int c = getchar();
    while (c != EOF)
    {
        putchar(c);
        c = getchar();
        printf(" hello\n");
    }
}

when I enter 12 and hit the return key this one produces:

12
1 hello
2 hello

and then there's the other one where I move printf() up, enter the same input

#include <stdio.h>

int main()
{
    int c = getchar();
    while (c != EOF)
    {
        putchar(c);
        printf(" hello\n");
        c = getchar();
    }
}

and it produces:

12
1 hello
2 hello

 hello

Why won't these two work the same way and why does that extra hello appear at the end of the second code.

Ryan
  • 35
  • 4
  • 2
    try changing it to `printf("hello %d\n", c);` – M.M Feb 01 '19 at 22:32
  • Possible duplicate of [Why is getchar() reading '\n' after a printf statement?](https://stackoverflow.com/questions/14765226/why-is-getchar-reading-n-after-a-printf-statement) –  Feb 01 '19 at 22:32

1 Answers1

3

Note, that you have provided an input of 3 characters - '1', '2' and a newline (\n). Given that let's trace what your programs are doing:

First snippet:

Read '1' -> 
Print '1' -> 
Read '2' -> 
Print "hello\n" -> 
Print '2' -> 
Read '\n' -> 
Print "hello\n" -> 
Print '\n' -> 
wait for more input

So the last thing printed is newline.

Second snippet:

Read '1' -> 
Print '1' ->  
Print "hello\n" -> 
Read '2' -> 
Print '2' -> 
Print "hello\n" -> 
Read '\n' -> 
Print '\n' -> 
Print "hello\n" -> 
wait for more input.

So it is first printing the newline and then "hello".

In short, both snippets perform an equal number of iterations, but in the first one the last printf(" hello\n") is blocked by the getchar when there is no more input. Which is not the case in the second snippet.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61