#include #include #include #include int main(int argc, char** argv) { { // close file when printer goes out of scope std::ofstream printer("test.txt"); if (!printer.is_open()) { std::cerr << "Error opening file for writing\n"; exit(2); } printer << " 123 456 789 \n"; printer << "987 865 \t 432\n"; printer << "1garbage 211 199\n"; printer << "666 777 888\n"; } std::ifstream reader("test.txt"); if (!reader.is_open()) { std::cerr << "Error opening file for reading\n"; exit(3); } // decalre two istream iterators, one with the file the other with end-of-stream // loop until the one first iterators equals the endofstream iterator for(std::istream_iterator iter(reader), endofstream; iter != endofstream; iter++) { int tmp; tmp = *iter; std::cout << "READ int: " << tmp << "\n"; // the "garbage" in the input will end the stream so the last int will be 1 } return 0; }