Need to read white space and other chars C++

泪湿孤枕 提交于 2019-12-02 09:30:00
#include <iostream>

using namespace std;

int main()
{
    char ch;
    int vowel_count = 0;
    int space_count = 0;
    int other_count = 0;

    cout << "Enter a string ends with #: " << endl;

    while(1)
    {
        cin.get(ch);
        if(ch == '#')
        {
            break;
        }

        if(ch == 'A' || ch == 'a'
            || ch == 'E' || ch == 'e'
            || ch == 'I' || ch == 'i'
            || ch == 'O' || ch == 'o'
            || ch == 'U' || ch == 'u')
        {
            ++vowel_count;
        }
        else if(ch == ' ')
        {
            ++space_count;
        }
        else
        {
            ++other_count;
        }
    }


    cout << "Vowels: " << vowel_count << endl;
    cout << "White spaces: " << space_count << endl;
    cout << "Other: " << other_count << endl;

    return 0;
}

No arrays

This line

if (character == 'A' || 'E' || 'I' || 'O' || 'U');

Is not doing what you think. It will always return true.

you need

if (character == 'A' || character == 'E' || character == 'I' || character == 'O' || character =='U')

and remove the semicolon as well at the end of that line

You can check for whitespace the exact same way. Common whitespace characters are space (' '), and horizontal tab ('\t'). Less-common are newline ('\n'), carriage return ('\r'), form feed ('\f') and vertical tab ('\v').

You can also use isspace from ctype.h.

Here:

while (cin >> character && character != '#')

You are skipping all white space. To prevent the operator >> from skiiping white space you need to explicitly specify this with the noskipws modifier.

while(std::cin >> std::noskipws >> character && character != '#')

Alternatively the same affect can be achieved with get

while(std::cin.get(character) && character != '#')

Next you are reading more characters outside the loop condition.

cin.get(character);

You already have a value in the variable 'character'. So remove both of these. The next iteration of the loop (in the while condition) will get the next character (as it is executed before the loop is entered).

Then fix you test as Tim pointed out.
You can then add another test for white space with:

if (std::isspace(character)) // Note #include <cctype> 
{  /* STUFF */ }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!