/* Lecture code 1.0 * * Code to read in a file containing a mix of integers and * plain-text strings, then output only the strings. This * leverages heavily off of stream failure and is a great way * to see how streams work in practice. * * To run this program, you'll need to have a file named * datafile.dat in the working directory. */ #include #include // For ifstream #include using namespace std; int main() { /* Open the file. In the version we used in class, * we did not check that the file was actually open, * but in practice we would do some checking. I've * put a sample error handler here. */ ifstream input("datafile.dat"); if(!input.is_open()) { /* cerr is the error-logging output stream, * which prints to the console. */ cerr << "Cannot open file!" << endl; return 0; } while(true) { /* Try to read an int. */ int myInt; input >> myInt; /* Check for end-of-file, break if necessary. */ if(input.eof()) break; /* If we fail, read it as a string. */ if(input.fail()) { input.clear(); // Very important! string word; input >> word; cout << word << " "; } } return 0; }