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;
}
user8930130
  • 39
  • 1
  • 8
  • Recommended reading: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Feb 09 '18 at 05:02
  • 1
    Where are you setting firstMinute secondMinute and numOfDishes? Just once? –  Feb 09 '18 at 05:03
  • And where is your routine for dealing with `getcontent`? – Killzone Kid Feb 09 '18 at 05:10

1 Answers1

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) //not checking for eof
{
    cout << firstMinute << ' ' << secondMinute << ' ' << numOfDishes << '\n';
}
BessieTheCookie
  • 4,571
  • 4
  • 13
  • 32