Reputation: 1421
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.
Upvotes: 0
Views: 101
Reputation: 154015
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.
Upvotes: 2