Trouble with fstream

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?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 #include <iostream>
#include <fstream>
#include <string>
using namespace 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;
}
You should always make sure to check that the file was found and opened correctly. Everything else looks ok.

1
2
if(!inFile)
    cout << "There was a problem with this file " << endl;
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.

Thanks.
closed account (S6k9GNh0)
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).
Topic archived. No new replies allowed.