首页 > 解决方案 > C ++提取和计算文本文件中的单词数

问题描述

我的任务是从文本文件中读取并计算字数,同时将文本显示到控制台。每当我调用“getString”函数时,“numCount”都会变为 0。如果我将“getString”函数注释掉,numCount 会显示正确的字数。因此,这两个函数看起来就像它们都被调用时才起作用,然后我遇到了这些问题。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void getFileInfo(ifstream &inFile);
int numOfWords(ifstream& inFile); // counts number of words
string getString(ifstream &inFile); // retrieves string from textfile


int main(){

    string fileName, words, str;
    ifstream inFile;
    int count;

    getFileInfo(inFile);
    str = getString(inFile);
    count = numOfWords(inFile);

    cout << "In the sentence, '" << str << "', there are " << count << " words " << endl;


}

void getFileInfo(ifstream &inFile){

    string fileName;

    do{

        cout << "Please enter the filename: " << endl;
        cin >> fileName;

        inFile.open(fileName.c_str());

        if(!inFile){

            cout << "Invalid try again" << endl;

        }
    }while(!inFile);

}

int numOfWords(ifstream& inFile){

    string fileName, words, str;
    int numCount =0;

    while(inFile >> words){
        ++numCount;
    }

    return numCount;

}

string getString(ifstream &inFile){

    string str;

    while(inFile)
        getline(inFile, str);

    return str;

}

标签: c++

解决方案


您的问题是您没有在之后重置流getString()

C++ iostreams 有一种隐喻光标,您读取的每一位都会将光标移动到下一位(因此您无需手动移动光标即可读取它)。inFile您的代码中的问题是光标位置在after的末尾结束getString(),这意味着循环getNumOfWords()永远不会运行。

您需要做的是在getString(). 例子:

std::string getString(ifstream& inFile) {
  ...
  inFile.clear() // <-- You may need this depending on your iostream implementation to clear the EOF failbit
  inFile.seekg(0, ios::beg);

  return str;

}

推荐阅读