0

I am trying to make this program ask the user to enter the name of a textfile and have it display the results that are in the textfile. When I run this program, its somewhat successful in the sense that it recognizes the textfile, but it outputs strange results. For example, I'm trying to get it to output the contents of a certain file that contains:

10 5 70    
5 15 85    
12 9 75    
10 6 60    
20 10 100    
15 8 95    
4 3 35    
20 10 200    
9 5 65

but it instead outputs just:

0 0 0

End of file reached

I really new to c++ but I've been trying to figure out for hours why my program isn't working and this is only a small chunk of the final program anyways. Thank you!

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;


int main()
{
    int  count, firstMinute, secondMinute, numOfDishes;
    string inputFileName;
    ifstream inputFile;

    cout << "Input file name: ";
    getline(cin, inputFileName);

    //Open input file
    inputFile.open(inputFileName);

    //check if messed up

    if (!inputFile.is_open())
    {
        cout << "Unable to open file." << endl;
        exit(1);
    }

    while (inputFile >> firstMinute >> secondMinute >> numOfDishes) 
    { 

        cout << firstMinute << ' ' << secondMinute << ' ' << numOfDishes << 
' ' << '\n';

    }

    cout << "End of file reached" << endl;

    inputFile.clear();
    inputFile.seekg(0);

    inputFile.close();
    return 0;
}
3
  • Recommended reading: Why is iostream::eof inside a loop condition considered wrong? Commented Feb 9, 2018 at 5:02
  • 1
    Where are you setting firstMinute secondMinute and numOfDishes? Just once? Commented Feb 9, 2018 at 5:03
  • And where is your routine for dealing with getcontent? Commented Feb 9, 2018 at 5:10

1 Answer 1

1

First of all, while(!inputFile.eof()) is not a good idea. More on that here.

Also, you simply never changed the value of firstMinute, secondMinute, and numOfDishes. Did you forget to do that in the loop?

I would have simply used the extraction operator instead of getline() like this:

while(inputFile >> firstMinute >> secondMinute >> numOfDishes)
{
    cout << firstMinute << ' ' << secondMinute << ' ' << numOfDishes << '\n';
}
Sign up to request clarification or add additional context in comments.

2 Comments

I replaced my while loop with yours but I am getting out put that now says just 0 0 0 still.
Ok I will edit my original question with the new code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.