Quick fstream question

Ok, so in the following code, the first line of the program "progfile.txt" literally reads "1". Its an int data type because I used another program to write an int to the file, and now this program is supposed to read and display it. However, for some reason, whenever I run this program, it keeps displaying the number "4273206" Why could that be?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int input;
    ifstream dataFile;

    dataFile.open("progfile.txt");
    dataFile >> input;
    cout << input;
    dataFile.close();
}
First of all you should check whether the file was opened. Also you can check visually is there your data in the file.
Good call, I put in an if-statement to validate if the file was being opened and its not. I'm really not sure why that could be though, here is my new code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int input;
    ifstream dataFile;
    dataFile.open("progfile.txt");

    if(dataFile)
    {
    dataFile >> input;
    cout << input;
    dataFile.close();
    }
    else
    {
        cout << "ERROR: Could not open file";
    }
}


When I run it, it displays the error message, any idea why the file might not be opening?
You should determine where your file was written. Maybe you should set the full file specification.
It was a location problem like you said, I moved the file to the right place and its functioning correctly. Thanks, I appreciate it
Topic archived. No new replies allowed.