[英]Using getchar() to count spaces, tabs, and newlines
我目前正在编写一个程序,该程序接受用户输入的句子并计算该句子中的空格,制表符和换行符的数量,然后输出值。
输入以!
终止!
或.
还是?
字符。
我的问题是,在输入末尾输入上述任何字符时,我的程序似乎都没有结束。
这是当前程序:
#include <stdio.h>
int main(void)
{
int space = 0, tab = 0, newline = 0;
int sentence;
printf("Enter a sentence (end by '.' or '?' or '!'):");
do{
sentence = getchar();
if(sentence == ' '){
++space;
}
else if(sentence == '\t'){
++tab;
}
else if(sentence == '\n'){
++newline;
}
}
while((sentence != '.')||(sentence != '!')||(sentence != '?'));
printf("Number of space characters: %d\n", space);
printf("Number of new line characters: %d\n", newline);
printf("Number of tabs: %d\n", tab);
return 0;
}
我很沮丧,任何帮助表示赞赏。
只需替换|| (或)与&&(和),因为在您的情况下,对于每个字符,三个条件中的两个始终为真,这就是while循环变为无限的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.