Search code examples
c++stringxcode9ifstream

Working with ifstream, data within file being called does not print


Here is my code, the goal is open a file, read the words within that file and keep a count of how many strings are within the file. My issue is that when I run my program and call the test file, only the first string of that file is read and printed, I'm not really sure what is going wrong with it, any help would be great.

here is what I have within my test file:

This &%file should!!,...

have exactly 7 words.


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

using namespace std;

int main(){

    ifstream inputFile;
    string fileName, inputRead;
    string sentinel = "quit";
    int count = 0;

    cout<< "what file do you want to open?: ";
    cin>> fileName;

    inputFile.open(fileName);

    while(!inputFile){
        cout<< "\nError opening file." <<endl;

        cout<< "Please enter filename correctly: ";
        cin>> fileName;

        inputFile.open(fileName);

    }

    while(fileName != sentinel){
        if(inputFile){

            inputFile >> inputRead;

            count++;

            cout<< endl;
            cout<< fileName << " data" <<endl;
            cout<< "*********************************\n" <<endl;

            cout<< inputRead <<endl;

            cout<< "\n*********************************" <<endl;
            cout<< fileName << " has " << count << " words." <<endl;

            cout<< "\nEnter another file name or type \"quit\" to end: ";
            cin>> fileName;
        }
    }

    inputFile.close();

    cout<< endl;

}

Solution

  • The problem is the if statement inside the while loop. If the filename is not equal to sentinel, you check if inputFile is valid. If so you execute the lines of code inside just once before getting a new file name. What you want is something like this:

    while(fileName != sentinel){
        cout<< endl;
        cout<< fileName << " data" <<endl;
        cout<< "*********************************\n" <<endl;
        while(inputFile >> inputRead){
    
            count++;
    
    
            cout<< inputRead <<endl;
    
        }
        cout<< "\n*********************************" <<endl;
        cout<< fileName << " has " << count << " words." <<endl;
    
        cout<< "\nEnter another file name or type \"quit\" to end: ";
        cin>> fileName;
    }