我试图找出我的 C 程序中制表符、空格和换行符的数量。代码是:
#include <stdio.h>
void main()
{
char c;
int tabs=0 , spaces=0 , nl=0 ;
printf("Provide the input");
scanf("%c" , &c);
while(c != EOF)
{
if(c == ' ')
spaces++;
else if(c == '\n')
nl++;
else if(c == '\t')
tabs++;
scanf("%c" , &c);
}
printf("blanks:%d\nspaces:%d\nnewlines:%d" , spaces , tabs , nl);
}
好吧,我希望它能做到这一点,但代码并没有超出接受输入阶段的范围。我究竟做错了什么?下面是我的命令行的样子:
[tejas@localhost The_C_Programming_Language]$ cc Exercise_1-8.c
[tejas@localhost The_C_Programming_Language]$ ./a.out
Provide the input seguiofgawie
gweuigwh
e u w f qw[uwf
[PHWUO FEFF
qah fuwpfyh fweor
(我一直按Return键,但没有结束。请帮忙。感谢您的阅读。这是我的第一个问题,希望我没有做错任何事......)
编辑:getchar()
也不起作用,我目前使用 Fedora 26 和 GEDIT 作为我的文本编辑器
编辑:getchar()
有效,为了发送 EOF 字符,应该在空行上按 Ctrl+D,如果你想用只需按一下 RETURN 键,将循环条件更改为 variable != '\n'
。我为传播错误信息道歉。
最佳答案
通过将扫描的 char 值与 EOF 进行比较,您在这里犯了一个小错误。引用另一个答案
EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1.
但是,由于您是从标准输入读取的,因此您无法将其作为单个字符输入,因为它将被视为 2 个字符,并且不会产生所需的结果。 简而言之,您的程序以预期的方式运行。为了让它退出输入模式,只需将您的 while 条件更改为您能够满足的条件。
关于C程序不退出输入模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632943/