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;
}
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';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.