简体   繁体   English

C ++使用while循环来计算用户输入的字符数

[英]C++ use a while loop to count the number of characters a user inputs

Write a program that asks for text input from the keyboard. 编写一个程序,要求从键盘输入文本。 The output of this program should be the amount of characters, the amount of words and the amount of newlines that have been typed. 此程序的输出应该是字符数,单词数量和已键入的换行符数量。 Multiple consecutive spaces should not be counted as multiple words. 多个连续空格不应计为多个单词。

The reading of characters from the keyboard can be stopped when the shutdown-code ^D (CTRL + D) is entered 输入关闭代码^ D(CTRL + D)时,可以停止从键盘读取字符

And my code is: 我的代码是:

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;
}

I know that ^D has the ASCII-value 4, but after I used (a=getchar())!=4 and input some words and ^D on the screen, and press 'enter', the program didn't show anything. 我知道^ D有ASCII值4,但在我使用(a = getchar())!= 4并在屏幕上输入一些单词和^ D并按'enter'后,程序没有显示任何内容。 Could someone help me please. 请有人帮助我。

The key point about handling Ctrl D that the question does not state, is that keystroke is the EOF (end of file) indicator for console programs. 关于处理问题未说明的Ctrl D的关键点是击键是控制台程序的EOF(文件结尾)指示器。 This means that when you type Ctrl D , getchar() does not return 4, but returns the special value EOF . 这意味着当您键入Ctrl D时getchar()不返回4,但返回特殊值EOF

Note that the value EOF is not a value that can fit in a char variable, so you have to declare int a instead of char a : 请注意,值EOF不是可以适合char变量的值,因此您必须声明int a而不是char a

int a;

while ((a = getchar()) != EOF)

By definition, EOF has no ASCII value. 根据定义,EOF没有ASCII值。 K&R tells us K&R告诉我们

getchar returns a distinctive value when there is no more input, a value that cannot be confused with any real character. 当没有更多输入时, getchar返回一个独特的值,这个值不能与任何真实字符混淆。

So you have to compare against the symbolic constant EOF. 所以你必须与符号常数EOF进行比较。 Its value is one which lies outside the range of valid ASCII codes. 它的值是有效ASCII码范围之外的值。

while ((c = getchar()) != EOF)

Also, c must be an int , not a char ; 此外, c必须是int ,而不是char ; this way, EOF fits. 这样,EOF适合。

Another issue in your program is your use of = (assignment) instead of == (comparison). 程序中的另一个问题是使用= (赋值)而不是== (比较)。 You write else if (a = ' ') but mean else if (a == ' ') . else if (a = ' ')你写else if (a = ' ')但是else if (a == ' ')表示else if (a == ' ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM