//-------------------------------------------------------------------- // // Example showing problem with getline() getprob.cpp // //-------------------------------------------------------------------- #include // For cin and cout #include // For file input/output #include // For strlen() void main() { ifstream inFile1("strline1.dat"), // Input files inFile2("strline2.dat"); char str[21], // Input string ch; // Input character // Read strings (one per line) from strline1.dat and output them. cout << "From strline1.dat: " << endl; while ( inFile1.getline(str,21,'\n') ) cout << "String: " << str << endl; cout << endl; // Read strings (one per line) from strline2.dat and output them. cout << "From strline2.dat: " << endl; while ( inFile2.getline(str,21,'\n') ) cout << "String: " << str << endl; cout << endl; // PROBLEM: The extra blank line occurred because the getline() // function stops reading when the character count reaches 20, // leaving the (unread) newline marker in the input stream. The // next call to getline() immediately reads this marker, stops, // and returns an empty string. // FIX: Add code after call to getline() to read characters // until the newline marker is read in. // Reset the file pointer to the start of the file. inFile2.seekg(0); // Reset pointer inFile2.clear(); // Clear file flags (including eof) cout << "---- After fix ----" << endl; cout << "From strline2.dat: " << endl; while ( inFile2.getline(str,21,'\n') ) { cout << "String: " << str << endl; if ( strlen(str) == 20 ) // Check if str full. If so, then do // newline marker not read in. inFile2.get(ch); // Read until newline found. while ( ch != '\n' ); } cout << endl; }