0

I tried to read in data from a text file using fstream but got wrong data.

ifstream fin ("C:\\Users\\rEgonicS\\Documents\\test.in");
int number;
fin >> number;
cout << number;

test.in is simply 12.
cout reads 4273190.
Can someone explain why this is so and how to fix it?

2
  • 1
    Is test.in literally "12" with quotations or is it just 12, and how is it encoded? If you aren't sure, what is the file size and what program did you save it with? Commented Jun 22, 2010 at 17:05
  • It is simply 12. I saved it in notepad and the file size is 4 bytes and 4KB on disk. Commented Jun 22, 2010 at 22:18

1 Answer 1

3

The most likely cause is that the file open failed. Check the status after opening, and also after reading; for a simple test, do something like this:

ifstream fin ("C:\\Users\\rEgonicS\\Documents\\test.in");
if (!fin) cout << "File open failed\n";
int number;
fin >> number;
if (!fin) cout << "File read failed\n";
cout << number;

This might give a further clue as to what's going on.

Sign up to request clarification or add additional context in comments.

2 Comments

I ran the above program and both "File open failed" and "File read failed" came up.
So that means it failed to open (it will then fail to read since it's not open). Is the path correct? Is the file readable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.