Reading data from text file

Jul 11, 2017 at 7:21am
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>

using namespace 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.
Last edited on Jul 11, 2017 at 7:22am
Jul 11, 2017 at 7:32am
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.
Jul 11, 2017 at 9:18am
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>

using namespace 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;
}

Jul 11, 2017 at 10:09am
Thanks jonnin for your kind help and Enoizat thanks for your tip.
Topic archived. No new replies allowed.