简体   繁体   中英

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

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. 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. This means that when you type Ctrl D , getchar() does not return 4, but returns the special value 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 :

int a;

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

By definition, EOF has no ASCII value. K&R tells us

getchar returns a distinctive value when there is no more input, a value that cannot be confused with any real character.

So you have to compare against the symbolic constant EOF. Its value is one which lies outside the range of valid ASCII codes.

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

Also, c must be an int , not a char ; this way, EOF fits.

Another issue in your program is your use of = (assignment) instead of == (comparison). You write else if (a = ' ') but mean else if (a == ' ') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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