Hi I need to create an int member function within a class that needs to display a menu and then prompts the user for a cin input that is both a number and between 1-5. It needs to loop the cin until a correct value is given displaying a different error message depending on the issue It then needs to be able to return that value.
Here is my code in c++
int ClassName::menu() {
cout << "Menu title" << endl;
cout << "1- option1" << endl;
cout << "2- op 2" << endl;
cout << "3- op 3" << endl;
cout << "4- op 4" << endl;
cout << "5- op 5" << endl;
cout << "0- exit program" << endl;
cout << "> ";
int flag = 1;
int value;
string input;
while (flag == 1) {
getline(cin, input);
value = stoi(input);
if (input[0] < '0' || input[0] > '5') {
cout << "Invalid Integer, try again: ";
input.clear();
}
else if (value < 0 || value > 5) {
cout << "[0<=value<=5], retry: ";
input.clear();
}
else {
flag = 0;
}
}
return value;
}
stoi()throws an exception if the conversion fails, but you are not catching the exception.After you have successfully converted the input string into an integer, there is no need to look at the individual characters of the input, especially since you are not even looking at the whole input.
But really, why are you reading the input into a string and then converting it into an integer in the first place? You should use
operator>>instead to read the input into the integer directly.Also, you are not using
cin.clear()correctly. It does not remove data from the input buffer. It resets the stream's error state, but you are calling it in a spot where the stream is not in an error state.Try this instead: