Reading Characters In A Loop
On the previous page we learned how to use getchar()
to read one character from the standard input, and putchar(c)
– or printf("%c", c)
– to print the character stored in c
to the standard output.
Two pages back, we discussed that assignments can be used in expression, because the value of any assignment operator equals to the assigned value.
Now it's a good time to combine these two ideas and write a while
loop that is "classic C": it combines an assignment and a comparison, all within a while
loop condition.
You remember that getchar()
returns EOF
when the input ends; and we also want to store the result of getchar()
in a variable. Let's figure out how to read all characters from the input until it ends, and print them back to the output.
Assuming we have a variable int c
, we can read one character into it with
c = getchar();
then we need to check if it's a EOF
and stop the iteration, so we'll probably have int finished
and set
if (c == EOF) {
finished = 1;
}
and finally, we'll print c
with
putchar(c);
all combined, we'll get something like this. Check that it works:
#include <stdio.h>
int main() {
int c, finished;
finished = 0;
while (!finished) { /* ! means "not" */
c = getchar();
if (c == EOF) {
finished = 1;
} else {
putchar(c);
}
}
return 0;
}
But let's start applying what we know about assignments. First of all, in C, it's common to combine the assignment and the EOF
check like this:
while (!finished) {
if ((c = getchar()) != EOF) {
putchar(c);
} else {
finished = 1;
}
}
But we can combine further if we notice that we only use finished
in a loop condition. The final version looks like this:
#include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
and it works in exactly the same way as the first approach, but is much shorter. Well, it's arguably harder to comprehend, unless you understand exactly how things work. If it's not immediately clear for you how it works, try spending some time to split in into parts:
c = getchar()
,(c = getchar()) != EOF
,while ((c = getchar()) != EOF)
,
and play it in your head to see what happens when getchar()
returns a valid character, and what happens when it returns a EOF
.
On the next page, we'll have an exercise!