// Reaper
#include <iostream>
#include <fstream>
#include <iomanip>
usingnamespace std;
int main()
{
int num1;
int num2;
int num3;
int num4;
int num5;
int total;
cout << "This will read the numbers from the file and add them together.\n\n";
ifstream datafile;
datafile.open("/home/reaper/Desktop/Programs/Chapter 3/Storing And Retrieving Numbers Using Files/Part 1/Storing and Retrieving Numbers/intergers.txt");
datafile >> num1;
datafile >> num2;
datafile >> num3;
datafile >> num4;
datafile >> num5;
total = num1 + num2 + num3 + num4 + num5;
cout << "\nThe numbers have been read in from the intergers.txt file.";
cout << "\n\n";
cout << "The total is " << total << endl;
datafile.close();
return 0;
}
my problem is at part 2, reading the number from the file. when i run part 2 it gives me a random number like -4999393249 and doesnt even read in my numbers, and even if in part 2 i change ifstream to ofstream it does the same thing. what am i doing wrong.
// Reaper
#include <iostream>
#include <fstream>
#include <iomanip>
usingnamespace std;
int main()
{
int num1;
int num2;
int num3;
int num4;
int num5;
int total;
cout << "This will read the numbers from the file and add them together.\n\n";
ifstream datafile;
datafile.open("/home/reaper/Desktop/Programs/Chapter 3/Storing And Retrieving Numbers Using Files/Part 1/Storing And Retrieving Numbers/intergers.txt");
if(datafile.fail())
{
cout << "Unable to open intergers.txt file." << endl;
return (1);
}
datafile >> num1;
datafile >> num2;
datafile >> num3;
datafile >> num4;
datafile >> num5;
cout << "\nThe numbers have been read in from the intergers.txt file.";
total = num1 + num2 + num3 + num4 + num5;
cout << "\n\n";
cout << "The total is " << total << endl;
datafile.close();
return 0;
}
Ok, i got the file to read in the answer for the numbers read from the file, but i cant seem to get it to actually display the numbers read from the file, all i can get it to do is display the total. How can i get it to read in the number from the file also.
Your problem is loop starting in line 29. Your data file has 5 values in it. You enter your while loop and read 5 values. Because you legitimately read the 5th value, the eof flag has not been set. So you go through the loop again.
The second time through, the << operator fails each time, so your values do not change. But, you have no control structures to get you out of the loop. So, you print out each of your values again.
I would suggest changing your while statement to an if statement.
Edit: Just get rid of the while loop. The if I was thinking of is already in line 23.