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

标签 c++ loops word-count isspace

我正在尝试计算输入文件中的大小写字母、数字位数和单词数。我已经完成了这个,但是,我的字数减少了一个。输入文件中有 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() 在读取文件中的最后一个字符后返回 true。所以你多来一次循环体。上次读取失败时,字符没有改变,并且因为它显然是一个空白字符,所以字数增加了。

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

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

关于c++ - 计算输入文件中的单词添加额外的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325833/

相关文章:

c++ - std::stringstream 和 str 方法

c++ - 在 shared_from_this() 中 boost weak_ptr_cast

javascript - Protractor :一旦找到元素就停止 while 循环

notifications - 添加Ckeditor的wordcount插件后禁用复制和粘贴

c++ - 使用正则表达式的高效字数统计方法

c++ - fatal error : QTextStream: No such file or directory

c - While 循环按引用传递字符数组

python - 如何从列表列表中提取所有唯一组合

Hadoop wordcount 无法运行 - 需要帮助解码 hadoop 错误消息

java - jFieldId int 对对象无效