我知道在谈到EOF之前,关于scanf的同一主题还有很多问题,但这里有一个我没有见过的特殊情况。假设我想要编写一个C程序,其中用户输入一个字符,该程序打印出该字符以及用户在按CTRL+D (EOF)键之前输入字符的次数。
这就是我所拥有的:
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
printf("time:%d, char:%c\n",i,thing);
i++;
}
return 0;
}然而,输出并不像预期的那样。如下所示:
f
time:0, char:f
time:1, char:
p
time:2, char:p
time:3, char:
m
time:4, char:m
time:5, char:我不太确定为什么i会再次递增,为什么printf会再次执行。也许我漏掉了什么。
发布于 2017-01-26 11:00:06
试一试
#include <stdio.h>
int main(){
char thing;
int i=0;
while(scanf("%c", &thing) != EOF){
if (thing!='\n') {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}发布于 2017-01-26 12:24:44
@user2965071
char ch;
scanf("%c",&ch);使用这样的代码片段,可以从流中读取任何ASCII字符,包括换行符、回车符、制表符或转义符。因此,在循环中,我将使用ctype函数之一测试符号读取。
如下所示:
#include <stdio.h>
#include <ctype.h>
int main(){
char thing;
int i=0;
while(1 == scanf("%c", &thing)){
if (isalnum(thing)) {
printf("time:%d, char:%c\n",i,thing);
i++;
}
}
return 0;
}至于我,我认为检查scanf返回EOF不是一个好主意。我更愿意检查好的读取参数的数量。
https://stackoverflow.com/questions/41865200
复制相似问题