1 year ago
#379196
STeN
C++ istream (cin) and problem with waiting for a ENTER key press
Please, is there a way I can wait for a single ENTER key press in all of the below cases? It works fine except when the std::getline()
is used, which consumes the \n
, and the ENTER needs to be pressed twice.
The code below works fine:
#include <iostream>
#include <limits>
using std::cout;
using std::cin;
using std::string;
void waitForENTERKeyPress();
int main ()
{
char c;
string s;
cout << "Enter c:"; cin >> c;
waitForENTERKeyPress();
cout << "Enter c:"; c = cin.get();
waitForENTERKeyPress();
cout << "Enter s:"; cin >> s;
waitForENTERKeyPress();
cout << "Enter s:"; std::getline(cin, s);
waitForENTERKeyPress();
return 0;
}
void waitForENTERKeyPress()
{
// Does not work with std::getline(...)
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Press an ENTER to continue...\n";
cin.get();
}
====[UPDATE]============================================
Let me rephrase what I am looking for: The way how to make the waitForENTERKeyPress()
function working in both cases – with \n
in the buffer, when cin
operator >>
or cin.get()
is used and also in cases the std::getline()
is used.
From what I understand it is not possible as there is not a way how to detect if the \n
is still in the buffer or not.
I have tried to use cin.rdbuf()->in_avail()
, but it always returns 0
.
c++
g++
0 Answers
Your Answer