I'm working on an assignment for one of my programming classes and ran into the following issue. As you can see the program outputs a menu and the user enters their choice (denoted as the char variable option). The issue is if the user enters a value such as 23 as an input the program takes the last entered char, in this case 3. This programming assignment specifically asked for this variable to be a char. Is there anyway to have the program recognize that the user entered two characters and not one?
#include <iostream>
usingnamespace std;
int main()
{
char c[2]; // size of char array doesn't actually matter as long as it's >=1
cin.get(c, 3); // reads 3-1=2 char from stream
if(cin.gcount() >= 2)
cout << "ERROR: TOO MANY CHAR" << endl;
cin.clear(); //clears cin error flags
cin.ignore(1000, '\n'); //clears 1000 char from stream buffer
return 0;
}
The gcount() is a function that counts how many times you use a cin function to get an input value. In this case gcount() counts the number of times we received input from get() cin function.