ifstream with getline and inputfile.eof() is not working.
This is not a homework but just a self study.
I am trying to read the information from inputFile and then loop through the data and display it. However; the below code falls into infinite loop. What am I doing wrong?
Code:
#include <iostream>#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("Store Sales.txt");
const int MAX_STORE = 5;
double sales;
int asteriks;
string storeName;
// Loop through each store and get the sales value
for(int storeCounter = 1 ; storeCounter <= MAX_STORE ; storeCounter++)
{
cout << "Enter the sales for store #" << storeCounter << ": " << '\n';
cin >> sales;
outputFile << "Store " << storeCounter << '\n';
outputFile << sales << '\n';
}
// Close the file
outputFile.close();
// Open the same file and show the asterisks graph bar
ifstream inputFile;
inputFile.open("Store Sales.txt");
// Test whether the file exists
if(inputFile)
{
cout << "SALES BAR CHART" << endl;
cout << "(Each *= $100)" << endl;
while(!inputFile.eof())
{
getline(inputFile,storeName);
cout << storeName << ": ";
inputFile >> sales;
asteriks = (sales / 100);
for(int i = 1; i<= asteriks; i++)
{
cout << "*";
}
cout << endl;
}
}
else
{
cout << "Cannot open the file!" << endl;
return 0;
}
// Close the file
inputFile.close();
return 0;
}