问题
#include <stdio.h>
main(void) {
char ch;
while (1) {
if ((ch = getchar()) != EOF)
{
break;
}
putchar(ch);
}
return 0;
}
How do I escape from this while
? I had tried with EOF but it didn't work.
回答1:
I think you mean:
int ch;
Because EOF
won't fit in a char
.
Also:
if ((ch=getchar()) == EOF)
break;
Your logic is backwards.
回答2:
This:
char ch;
is wrong, EOF
doesn't fit in a char
. The type of getchar()
's return value is int
so this code should be:
int ch;
Also, as pointed out, your logic is backwards. It loop while ch
is not EOF
, so you can just put it in the while
:
while((ch = getchar()) != EOF)
回答3:
check with the while. It's more simple
while((ch=getchar())!= EOF) {
putchar(ch);
}
The EOF is used to indicate the end of a file. If you are reading character from stdin, You can stop this while loop by entering:
EOF
= CTRL + D (for Linux)EOF
= CTRL + Z (for Windows)You can make your check also with
Escape
chracter or\n
charcter
Example
while((ch=getchar()) != 0x1b) { // 0x1b is the ascii of ESC
putchar(ch);
}
来源:https://stackoverflow.com/questions/13803072/how-to-exit-a-while-loop