![](/img/trans.png)
[英]c++ program that inputs a sentence from the user and counts the number of words and characters in the sentence
[英]C++ use a while loop to count the number of characters a user inputs
编写一个程序,要求从键盘输入文本。 此程序的输出应该是字符数,单词数量和已键入的换行符数量。 多个连续空格不应计为多个单词。
输入关闭代码^ 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并按'enter'后,程序没有显示任何内容。 请有人帮助我。
关于处理问题未说明的Ctrl D的关键点是击键是控制台程序的EOF(文件结尾)指示器。 这意味着当您键入Ctrl D时 , getchar()
不返回4,但返回特殊值EOF
。
请注意,值EOF
不是可以适合char
变量的值,因此您必须声明int a
而不是char a
:
int a;
while ((a = getchar()) != EOF)
根据定义,EOF没有ASCII值。 K&R告诉我们
当没有更多输入时,
getchar
返回一个独特的值,这个值不能与任何真实字符混淆。
所以你必须与符号常数EOF进行比较。 它的值是有效ASCII码范围之外的值。
while ((c = getchar()) != EOF)
此外, c
必须是int
,而不是char
; 这样,EOF适合。
程序中的另一个问题是使用=
(赋值)而不是==
(比较)。 else if (a = ' ')
你写else if (a = ' ')
但是else if (a == ' ')
表示else if (a == ' ')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.