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

时间:2012-02-08 00:33:41

标签: c++ io char while-loop file-io

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;

我正在尝试输入一个句子,读取它有多少个元音,空格和其他字符。但是vowelCount永远不对,我无法让它将相同的句子写入输出文件。任何提示?

2 个答案:

答案 0 :(得分:0)

您尚未显示变量vowelCount的声明/初始化。我假设您只使用如下语句声明(并且未初始化):

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

在C ++中,int变量没有默认值。如果您编写了此类代码,则可以通过使用以下语句显式初始化其值来纠正它:

int vowelCount = 0;

此外,你的循环在每次迭代时读取2个字符(跳过两个字符中的一个)并且你错过了元音Y

更正后的示例如下:

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

答案 1 :(得分:0)

就像pmr的注释所示,问题是你在每次循环迭代时读取两个字符,但只检查第一个。这两个语句都使用stdin中的字符:

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

您需要做的就是:

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