0

I'm having a problem reading an integer from a file. As for my knowledge it should work. Can you tell me what have I done wrong here?

 int fileCount = 0; ifstream listFileStream ( fileName ); if ( listFileStream.is_open() ) { listFileStream >> fileCount; cout << fileCount; } 

It only prints 0 even though the first line of the file is 28.

4
  • Try reading a line at a time. see here Commented Nov 28, 2013 at 6:15
  • If I change the variable type to string it gives this... 'fileCount = "ÿþ2"' Commented Nov 28, 2013 at 6:19
  • 2
    @SankaD I think you have some unexpected characters at the start of your file. Could even be the Byte Order Mark (BOM). Commented Nov 28, 2013 at 6:20
  • Ah... I deleted the file and copied the content into a new file with the same name and now it works... Thanks. Commented Nov 28, 2013 at 6:23

1 Answer 1

2

You should always check that you read attempt was successful:

if (listFileStream >> fileCount) { process(fileCount); } 

If the read isn't successful you can try to recover from it or report an error. Here is one way you might try to recover: restore the stream to good state and ignore the first character:

listFileStream.clear(); listFileStream.ignore(); 

Without restoring the stream to a good state all input attempts would be ignored. Once the offending character is removed you would retry the read.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.