首页 > 解决方案 > 程序计数辅音错误

问题描述

我正在尝试制作一个计算文本文件中所有元音和所有辅音的程序。但是,如果文件中有诸如 cat 之类的单词,则它说有 3 个辅音和 1 个元音,而应该有 2 个辅音和 1 个元音。


#include <string>
#include <cassert>
#include <cstdio>

using namespace std;

int main(void)
{
    int i, j;
    string inputFileName;

    ifstream fileIn;
    char ch;
    cout<<"Enter the name of the file of characters: ";
    cin>>inputFileName;
    fileIn.open(inputFileName.data());
    assert(fileIn.is_open());
    i=0;
    j=0;



    while(!(fileIn.eof())){
        ch=fileIn.get();

        if (ch == 'a'||ch == 'e'||ch == 'i'||ch == 'o'||ch == 'u'||ch == 'y'){
            i++;
        }

        else{
            j++;
        }
    }

    cout<<"The number of Consonants is: " << j << endl;
    cout<<"The number of Vowels is: " << i << endl;

    return 0;
}

标签: c++stringfilecharactercounting

解决方案


在这里您检查eof状态是否已设置,然后尝试读取char. eof在您尝试读取超出文件末尾之前不会设置,因此读取char失败,但您仍然会计算char

while(!(fileIn.eof())){
        ch=fileIn.get();   // this fails and sets eof when you're at eof

因此,如果您的文件仅包含 3 chars, c,a并且t您已阅读 ,t您会发现eof()未设置。它将在您尝试阅读下一个时设置char

更好的方法是检查fileIn提取后是否仍处于良好状态:

while(fileIn >> ch) {

有了这个,计数应该加起来。但是,所有特殊字符都将被视为辅音。为了改进这一点,您可以检查是否char是一个字母:

#include <cctype>

// ...

    while(fileIn >> ch) {
        if(std::isalpha(ch)) {        // only count letters
            ch = std::tolower(ch);    // makes it possible to count uppercase letters too
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
                i++;
            } else {
                j++;
            }
        }
    }

推荐阅读