I am working my way through "Starting out with c++" by Tony Gaddis.
I created a .txt file with only "100" entered there and tried to read the file using c++ with the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inFile;
int val1;
inFile.open("numeri.txt");
inFile>>val1;
cout<<val1;
inFile.close();
return 0;
}
The output is a random number each time the program is run.
P.S:I am using codeblocks and GNU GCC compiler.
make sure the file is in the same folder as your program, spelled correctly, same caps on unix systems. Or use infile.good() or one of the other test functions to see if it opened correctly.
As a secondary point, in addition to what jonnin suggested, you could get used to initialising your variables as soon as you define them.
In this case, if you had initialised “val1“ to some value, let’s say 0, you could have easily inferred from the output the program was not reading from the file.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inFile;
int val1 = 13; // initializing my variable
inFile.open("numeri.txt");
inFile>>val1;
cout<<val1; // print "13" when "100" is expected: I may suspect my
// program isn't reading from the file
inFile.close();
return 0;
}