【发布时间】:2018-01-22 01:57:27
【问题描述】:
编写一个程序,要求从键盘输入文本。这个程序的输出应该是字符的数量、单词的数量和已输入的换行符的数量。多个连续空格不应计为多个单词。
当输入关闭代码^D (CTRL + D)时,可以停止从键盘读取字符
我的代码是:
int main()
{
char a;
int characters = 0;
int words = 1;
int newlines = 0;
printf("Input something\n");
while ((a = getchar())!=4)
{
if (a >= 'a'&&a <= 'z' || a >= 'A'&&a <= 'Z')
characters++;
else if (a = ' ')
words++;
else if (a = '\n')
newlines++;
}
printf("The number of characters is %d\n", characters);
printf("The number of words is %d\n", words);
printf("The number of newlines is %d\n", newlines);
return 0;
}
我知道 ^D 的 ASCII 值是 4,但在我使用 (a=getchar())!=4 并在屏幕上输入一些单词和 ^D 后,按“回车”,程序没有不显示任何东西。谁能帮帮我。
【问题讨论】:
-
因为是c++功课,我觉得C和C++的基础知识差不多
-
完全没有@一帆
-
好吧,可能因为我是新手,你能告诉我为什么我的代码不正确
-
问题要求多个连续的空格不应该算作多个单词。在我的代码中,我无法将多个连续空格作为一个空格。