cgetcharputchar

C Simple Code Involving getchar() and putchar() Unexpected Output


As I was following an example from a book,

#include <stdio.h>

main()
{
        int c;

        c = getchar();
        while (c != EOF) {   
                putchar(c)
                c = getchar();
        }
}

I thought it would make more sense to read character first, then print it so switched putchar and getchar around

c = getchar();
putchar(c);

now when I run it, what happens is the first output of putchar is missing the first character of c? This is the output:

kingvon@KingVon:~/Desktop/C$ ./a.out
first letter is missing?
irst letter is missing?
but now it is not 
but now it is not

This is interesting, why does this happen?


Solution

  • Because you're getting a character before the loop. That means c is equal to that first character, but in the loop it's getting every character after that. So,

    Get: f
    Start the loop
    Get: i
    Print: i
    And so on