I was wondering what's happening in this code from K&R C:
#include <stdio.h>
int main() {
double nc;
for (nc = 0; getchar(); ++nc) {
;
}
printf("%.0f\n", nc);
}
When I run the code (OS X El Capitan), the for
loop doesn't finish and I can't get to the printf
statement.
The getchar()
returns the obtained character on success or EOF
on failure. Reference here .
Try this
for (nc = 0; getchar() != EOF; ++nc) { }
Note that, Enter doesn't means EOF
, it means newline or '\\n'
.
Look at the header stdio.h
, says,
#define EOF (-1)
Here you can see how to simulate an EOF.
Windows: Ctrl+Z
Unix : Ctrl+D
So long story short, you can put any condition in the for
loop, like
for (nc = 0; getchar() != '\n'; ++nc) { } // break the loop if enter pressed
for (nc = 0; getchar() != 'c'; ++nc) { } // break the loop if c pressed
.
.
.
getchar()
waits on the input from stdin and even if you enter any character it would be read by getchar()
but that doesn't make you get out of the loop.
So you need to add some condition on the return value of getchar()
to gracefully exit the loop.
For Eg:
for(;getchar() != EOF;)
{
}
If you want to return on newline character then check should be getchar() != '\\n'
PS: I have just shown how to check the return value , for me the exit condition is EOF
it might vary for you.
This loop
for (nc = 0; getchar(); ++nc) {
;
will iterate until getchar() returns 0. To achieve this without rewritting the program as others are suggesting you should for example in Windows press key combination Ctrl + @
and then press Enter. The value of key combination Ctrl + @
is equal to 0.
If you revise your code to make it:
#include <stdio.h>
int main() {
double nc;
while (getchar() != EOF) {
++nc;
}
printf("\n%.0f\n", nc);
}
Then if you run it in a terminal window and enter the following:
abcCtrl-D
you will get the output:
abc
3
(The Ctrl-D is the EOF character)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.