Reputation:
I created a for loop in my program that makes it so you have to press enter to continue. I did this Using cin.ignore(). This is the basic idea of the code that I am using.
for (int i = 0; i < 5; i++) { // loop will do it for each player data
cout << "Press Enter to Continue ";
cin.ignore();
system("cls");
cout << "Playes Data" << endl;
}
This code works fine until the player decides to input something rather than just press enter. From what I understand, because the player inputted something, this means that there will be a buffer. You can get rid of the buffer from just using cin.ignore. This makes it so it skips an iteration and the player doesn't have to press enter to continue. I have just included a second cin.ignore, but I don't want them to have to press enter twice. Is there some way to use the second cin.ignore only if there is a buffer, or is there some other way to deal with this?
Upvotes: 0
Views: 882
Reputation: 180500
You can replace
cin.ignore();
with
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Where the second option will ignore all characters including the newline the enter key puts into the stream.
Upvotes: 1
Reputation: 595827
There is always a buffer. Calling std::cin.ignore()
by itself, with no parameter values, simply skips the next char in the buffer, which may or may not be a '\n'
char from an ENTER press.
To skip everything in the buffer, up to the next ENTER press, use std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n')
.
Upvotes: 3