1

我正在尝试计算输入文件中的大写和小写字母、位数和单词数。我已经完成了这个,但是,我的字数减少了一个。输入文件中有 52 个单词,但我的计数是 53。这是什么原因造成的?所有其他(大写,小写和数字)都是正确的......

这是我所拥有的:

using namespace std;

int main()
{
        fstream inFile;
        fstream outFile;
        string fileName("");
        string destName("");
        char c = 0;
        ///////string wrdRev("");/////////
        int numCount = 0;
        int capCount = 0;
        int lowCount = 0;
        int wordCount = 0;

        cout << "Please enter file name: ";
        getline(cin, fileName);
        cout << endl;

        inFile.open(fileName, ios::in);

        if (inFile.good() != true) {
                cout << "File does not exist!\n" << endl;
                return 0;
        }
        else{
                reverse(fileName.begin(), fileName.end());
                destName += fileName;
        }   




 outFile.open(destName, ios::in);

        if (outFile.good() == true){
                cout << "File '" << destName << "' already exists!\n" << endl;
                return 0;
        }   
        else {
                outFile.clear();
                outFile.open(destName, ios::out);


        while(inFile.good() != false){
                inFile.get(c);

                if(isupper(c)){
                        capCount++;
                }
                else if(islower(c)){
                        lowCount++;
                }
                else if(isdigit(c)){
                        numCount++;
                }
                else if(isspace(c)){
                        wordCount++;
                }

        }
                outFile << "There are " << capCount << " uppercase letters." << endl;
                outFile << "There are " << lowCount << " lowercse letters." << endl;
                outFile << "There are " << numCount << " numbers." << endl;
                outFile << "There are " << wordCount << " words." << endl;



        }

        inFile.close();
        outFile.close();

        return 0;


}

任何帮助,将不胜感激。谢谢你。

4

1 回答 1

4

ios::good()true读取文件中的最后一个字符后返回。所以你多来一次循环体。上次读取失败时,字符保持不变,并且因为它显然是一个空白字符,所以字数增加了。

您通常不应该使用 thisgood()eof()作为输入结束的测试。改为这样做:

while (inFile.get(c)) {
    //...
}
于 2016-02-10T21:06:46.207 回答