Reputation: 61
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?
Upvotes: 1
Views: 69
Reputation: 464
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
Upvotes: 2
Reputation: 782285
The problem is that now you're not printing the character that you read with getchar()
before the loop, so you don't print the first character.
If you want to do the getchar()
first, put it into the while()
condition.
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c)
}
}
Upvotes: 0