【问题标题】:Counting words from input file adding extra word?计算输入文件中的单词添加额外的单词?
【发布时间】:2016-05-21 10:22:36
【问题描述】:

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


}

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

【问题讨论】:

  • 您能发布导致错误的字符串/输入文件吗?还是不管输入如何都会发生?
  • @LukeG 输入文件内容:这是 hw3 的测试文件 这个文件有多少个大写字母?这个 F1le 中有多少个小写字母? H0W 文件中有许多 dIg1ts ar3 1N?将 1npU7 N4​​m3 int0 反转,将 Lines 反转到它们的 opp05173 coutnerpart 在 File 中找到 characTer5 的总数,这只是一个示例文件。关键是它应该计算用户输入的输入文件中的任何内容。

标签: c++ loops word-count isspace


【解决方案1】:

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

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

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

【讨论】:

  • 这确实有效,并且给了我正确的字数。 .good() 在这种情况下到底做了什么?是把状态位读成一个字吗?
  • 你确实回答了这个问题。网站还是新手。你的整个评论没有显示,因为我没有点击它。感谢您的回复。
  • @Ry23 没问题,另见stackoverflow.com/questions/5605125/…
猜你喜欢
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
相关资源
最近更新 更多