[英]How to exit a while-loop?
#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
? 如何从这个逃生
while
? I had tried with EOF but it didn't work. 我曾尝试使用EOF但它没有用。
I think you mean: 我想你的意思是:
int ch;
Because EOF
won't fit in a char
. 因为
EOF
不适合char
。
Also: 也:
if ((ch=getchar()) == EOF)
break;
Your logic is backwards. 你的逻辑是倒退的。
This: 这个:
char ch;
is wrong, EOF
doesn't fit in a char
. 是错的,
EOF
不适合char
。 The type of getchar()
's return value is int
so this code should be: getchar()
的返回值类型是int
所以这段代码应该是:
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
: 它循环而
ch
不是EOF
,所以你可以把它放在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. EOF用于指示文件的结尾。 If you are reading character from stdin, You can stop this while loop by entering:
如果您正在从stdin中读取字符,则可以通过输入以下内容来停止此循环:
EOF
= CTRL + D (for Linux) EOF
= CTRL + D (适用于Linux) EOF
= CTRL + Z (for Windows) EOF
= CTRL + Z (适用于Windows)
You can make your check also with Escape
chracter or \\n
charcter 您也可以使用
Escape
chracter或\\n
charcter进行检查
Example 例
while((ch=getchar()) != 0x1b) { // 0x1b is the ascii of ESC
putchar(ch);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.