I/O from a text file

Im getting some crazy error messages.I have to use the data from the text file to calculate the avg mpg from each car. When I run the program I get 77 errors under the text.file<<





#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
#include<string>
using namespace std;
int main()
{

double car_num, miles, used_gas, mpg, total_miles = 0,
total_gas = 0, avg_mpg[5];
int i = 0;

string line;
ifstream textfile;
textfile.open("cars.txt");
if (textfile.fail())
{
cout << "Can Not Find File\n";
system("pause");
exit(1);
}
while (getline(textfile, line))
{
cout << line << '\n';
}
textfile.close();

while (!textfile.eof())
{
total_miles += miles;
total_gas += used_gas;
avg_mpg[i] = miles / used_gas;
i++;
textfile >> car_num >> miles >> used_gas >> mpg;
}
textfile.close();

textfile << "Total Miles = " << total_miles << "\n";
textfile << "Total Gas = " << total_gas << "\n";
textfile << "Average MPG for all the cars = ";
for (i = 0; i <5; i++)
textfile << avg_mpg[i] << " ";
textfile.close();

system("pause");
return 0;
1) You are trying to manipulate closed file
2) You are trying to write output to the input file.
Topic archived. No new replies allowed.