I am learning C from the book "The C Programming Language"; my question is about something I observed while trying to reformulate with few lines of code regarding input and output: why is it needed to give the getchar() function a value of a certain integer in order to have it store all the text in the input? For example with this code putchar() is printing all that I type;
int c;
while ((c = getchar()) != EOF)
putchar(c)
But, why isn't it the same if I write:
while (getchar() != EOF)
putchar(getchar());
In the latter case, for example, if I write "okok", the program is then printing "kk".
I think the reason is within some property of getchar(), that I wasn't able to get; for example, if I write a character counting program, and I want to exclude new lines, I also observed that it's working if I write it as:
int nc, c;
nc = 0;
while ((c = getchar()) != EOF)
if (c != '\n')
++nc;
printf("%d", nc);
But it's not able instead to distinguish correctly the '\n' when using getchar() directly instead of c integer:
while ((c = gethar()) != EOF)
if (getchar() != '\n')
++nc;
printf("%d", nc);
My purpose it is just to understand, as I wouldn't like to learn this just by memory, and in the book it is written that getchar() is working using int values, so I wonder if there is something that I missed about properties of getchar() despite reading several times, also searching in different questions in stack overflow regarding the getchar() topic.
When you write
while (getchar() != EOF)
putchar(getchar());
It always
Therefore, in your "okok" example, the odd 'o' characters are read, compared to EOF
and discarded, and only the even 'k's make it through.
If you wanted to print all of the input characters, you would have to restructure your code. For example, to call getchar()
once, save the return value to a variable, then use the already read value twice - check it for EOF
and print it.
while (1) { /* loop forever (until break is called) */
int ch = getchar();
if (ch == EOF)
break;
putchar(ch);
}