Matt M
Matt M

Reputation: 33

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

My task is to read from a text file and count the number of words while displaying the text to the console. Whenever I call my "getString" function, my "numCount" goes to 0. if I comment my "getString" function out the numCount shows the correct number of words. So both functions look like they work it just when they are both called then I get these problems.

#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;

}

Upvotes: 1

Views: 907

Answers (1)

Object object
Object object

Reputation: 2054

Your problem is that you are not resetting the stream after getString()

C++ iostreams have a sort of metaphorical cursor, where every bit you read moves the cursor to the next bit (so you can read it without having to manually move the cursor). The problem in your code is that the cursor position ends up at the end of inFile after getString(), meaning the loop in getNumOfWords() never runs.

What you need to do is reset the stream after getString(). Example:

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;

}

Upvotes: 2

Related Questions