简体   繁体   English

C ++简单IO元音计数程序

[英]C++ simple IO vowel count program

char ch;
//Get data from user 
cout << "Enter your sentence on one line followed by a # to end it: " << endl;

while (cin >> character && character != '#') 
{
    cin.get(ch); 
    ch = static_cast<char>(toupper(ch));
    outFile << ch;

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

    }
}
outFile << "number of vowels: " << vowelCount << endl;

I am trying to input a sentence, read how many vowels, blank spaces, and other characters it has. 我正在尝试输入一个句子,阅读它有多少个元音,空格和其他字符。 But the vowelCount is never right and I can't get it to write the same sentence to output file either. 但是vowelCount永远是不正确的,我也无法用它写相同的句子来输出文件。 Any hints? 有什么提示吗?

You have not shown the declaration / initialization of the variable vowelCount . 您尚未显示变量vowelCount的声明/初始化。 I assume you have only declared (and not initialized) it using a statement like: 我假设您仅使用以下语句声明(而不初始化)它:

int vowelCount; // notice the variable is not initialized.

In C++, int variables have no default value. 在C ++中, int变量没有默认值。 If you have written such code, you can correct it by explicitly initializing its value with a statement like: 如果您已经编写了这样的代码,则可以通过以下语句显式初始化其值来更正它:

int vowelCount = 0;

Moreover, your loops reads 2 characters at each iteration (skipping one out of two characters) and you are missing the vowel Y . 此外,您的循环在每次迭代中读取2个字符(从两个字符中跳过一个),并且您丢失了元音Y

The corrected example would look like: 更正后的示例如下所示:

//Get data from user 
cout << "Enter your sentence on one line followed by a # to end it: " << endl;

int vowelCount = 0;
while (cin >> character && character != '#') 
{
    character = toupper(character);

    if (character == 'A' || character == 'E' || character == 'I' || character == 'O'
                || character == 'U' || character == 'Y')
    {
        vowelCount ++;

    }
}
outFile << "number of vowels: " << vowelCount << endl;

Just like pmr's comment indicates, the problem is that you are reading in two characters with each loop iteration, but only checking the first one. 就像pmr的注释所指示的那样,问题在于您每次循环迭代都读取两个字符,但是仅检查第一个字符。 Both of these statements consume a character from stdin: 这两个语句都使用stdin中的字符:

cin >> character
...
cin.get(ch)

all you need to do is this: 您需要做的就是:

while (cin >> character && character != '#') 
{
    character = static_cast<char>(toupper(character));

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

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