The following function is supposed to read and print five lines from a file and than prompt the user for five lines more or to quit:
void Reader::readNotes() {
std::cout << std::endl;
std::ifstream file("note.txt");
if (!file.is_open()) {
std::cerr << "Unable to open file: note.txt" << std::endl;
return;
}
const int linesPerPage = 5;
int linesPrinted = 0;
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
++linesPrinted;
if (linesPrinted >= linesPerPage) {
std::string input;
std::cout << std::endl;
std::cout << "Press Enter for more, or type 'q' to quit: " << std::endl;
std::getline(std::cin, input);
if (input == "q") {
break; // Exit loop if user types 'q'
}
linesPrinted = 0; // Reset lines printed for next page
}
}
file.close();
}
The problem is that, at the very first print, ten lines are being printed instead of five.
The output I'm getting from the first print is:
Line 1
Line 2
Line 3
Line 4
Line 5
Press Enter for more, or type 'q' to quit:
Line 6
Line 7
Line 8
Line 9
Line 10
Press Enter for more, or type 'q' to quit:
The intended output is:
Line 1
Line 2
Line 3
Line 4
Line 5
Press Enter for more, or type 'q' to quit:
All the other prints after that, if the user presses enter, print five lines as expected. The only print that goes wrong is the first.