簡體   English   中英

C++提取和計算文本文件中的單詞數

[英]C++ Extracting and counting number of words in a text file

我的任務是從文本文件中讀取並計算單詞數,同時將文本顯示到控制台。 每當我調用“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;

}

你的問題是你沒有在getString()之后重置流

C++ iostreams 有一種隱喻的游標,您讀取的每一位都將光標移動到下一位(因此您無需手動移動光標即可讀取它)。 您的代碼中的問題是光標位置在getString()之后的inFile末尾結束,這意味着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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM