Originally Posted by
dnguyen1022
May I ask how that would control the looping? When the istream runs out of input what does it exactly return? And what kind of errors would you come across?
And are there other reasons?
It is quite typical that stream input functions return the same stream which in turn can be tested in boolean context (is stream good to continue after an attempt to input something?). Therefore it would be quite natural to make your own input routines also return the stream, so they can be used in the same way as for example getline.
Typical errors that might happen is failure to open file, unexpected contents (trying to input a number but the file does not contain numeric data at that spot) and reaching the end of file. You can test these conditions with the eof(), fail() and rdstate() function.
Example:
Code:
#include <iostream>
#include <fstream>
void test_io_flags(const char* filename, const char* contents)
{
std::ofstream fout(filename);
fout << contents;
fout.close();
int n;
std::ifstream fin(filename);
while (fin >> n) {
std::cout << "Read " << n << '\n';
}
std::cout << "eof() = " << fin.eof() << ", fail() = " << fin.fail() << "\n\n";
}
int main()
{
std::cout << std::boolalpha;
const char* filename = "untitled1.tmp";
test_io_flags(filename, "10 20 30"); //contains numbers as expected
test_io_flags(filename, "5 hello 8"); //not all numbers, "corrupted" file contents
}
In the first test the file contains all numbers as expected. After everything is input both eof and fail bit are set: the entire file has been read and the last input attempt failed (because there was nothing more left to read).
In the second test the file is "corrupt" containing a non-numeric string. This time eof bit is not set, meaning an input error happened before the entire contents could be read.