So I was going through my textbook and doing some of the fstream examples. I got through some of them except the ones where I am trying to read from a file. In my previous program I entered the following numbers 50, 40, 30, 20 to be read in this program. When I run this program I get " -858993460 -858993460 -858993460 -858993460. Their sum is 858993456." What exactly am I doing wrong?
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
ifstream inFile;
int value1, value2, value3, value4, sum;
//Open the file.
inFile.open("Numbers.txt");
//Read the four numbers from the file.
inFile >> value1;
inFile >> value2;
inFile >> value3;
inFile >> value4;
//Close the file.
inFile.close();
//Calculate the sum of the numbers.
sum = value1 + value2 + value3 + value4;
//Display the four numbers.
cout << "Here are the numbers: \n"
<< value1 << " " << value2
<< " " << value3 << " " << value4
<< endl;
// Display the sum of the numbers.
cout << "Their sum is: " << sum << endl;
cin.get();
return 0;
}
So I added the code you wrote and it did tell me there was a problem with the file. I copied the txt file into same file my project was in and it fixed it. I rechecked my book for an example.
inputFile.open("C:\\data\\inventory.txt")
If I add that code I wouldn't have to make multiple copies of the txt file.
As a rule of thumb, you probably should never assume something was successful unless you can't afford to check for errors (which is almost never the case).