#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.
I think you mean:
int ch;
Because EOF
won't fit in a char
.
Also:
if ((ch=getchar()) == EOF)
break;
Your logic is backwards.
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)
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);
}
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.