#include <stdio.h>
int main() {
int c;
while(getchar() != EOF) {
if (getchar() == ' ') {
c++;
}
printf("%i", c);
}
}
我意识到输入一个像你正确阅读的句子
我实现了\ n \ n \ n \ n \ n \ n \ n \ n \ n \ n ...
我相信它是如何读取的,getchar()没有达到EOF以使条件在括号中为假。
我的目标是创建一个程序,从我那里获取输入...如果在达到EOF时计数器上有任何空格,则读取它。继续读取它的条件变为假,计数器值在屏幕上打印出来告诉我在我的整个输入中有多少空格..
这不可能吗?这就是为什么人们只使用scanf()?
这是我在尝试某些东西时得到的输出
user@user:/c# ./a.out
hello stackoverflow this does not do what i want it to
001111111222223344445666677
发布于 2018-07-18 16:29:24
你需要将结果getchar()
放入变量中:
int ch;
while ((ch = getchar()) != EOF)
你不应该getchar()
第二次调用它来检查它是否是一个空格,因为那将读取第二个字符,所以你将测试每个其他字符,只需比较变量:
if (ch == ' ')
如果你想看到空格的总数,把它printf()
放在循环的末尾,而不是在它里面。
所以整个事情应该是这样的:
#include <stdio.h>
int main() {
int counter=0;
int ch;
while((ch = getchar()) != EOF) {
if (ch == ' ') {
counter++;
}
}
printf("%i\n", counter);
}
要从EOF
终端发送Control-d,请Control-z在Windows上键入Unix 。
https://stackoverflow.com/questions/-100005595
复制相似问题