计算输入文件中的单词添加额外的单词?

Counting words from input file adding extra word?

我正在尝试计算输入文件中的大小写字母、数字位数和单词数。我已经完成了这个,但是,我的字数减少了一个。输入文件中有 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;


}

如有任何帮助,我们将不胜感激。谢谢。

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

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

while (inFile.get(c)) {
    //...
}