This is so common that I thought I could easily find existing code, but all the search results were not what I want. What I want is:
- Pressing 'Y' or 'y' (no enter) becomes YES.
- Pressing enter becomes YES, because YES is the default.
- Pressing 'N' or 'n' (no enter) becomes NO.
- All other keypresses are ignored.
The following code only works if I press enter after typing 'y' or 'n'. How can I get the value immediately as the user presses 'y'?
using namespace std;
int main()
{
cout << "Do it? (Y/n): ";
while (true)
{
auto input = cin.get();
if (input == '\n' || input == 'y')
{
cout << "YES";
break;
}
else if (input == 'n')
{
cout << "NO";
break;
}
}
cout << "Done.";
cin.get();
}