Это фрагмент кода из моей программы. Функция getMenuChoice () успешно выполняется в Visual Studio при вводе целых чисел, но при вводе символа она входит в бесконечный цикл. Мне сказали, что моя программа не должна учитывать, что пользователь вводит символ, но когда я отправляю его, оценочная машина сообщает мне, что он «превысил допустимую длину». Помимо того, что он не учитывает символы, я не уверен, что не так с функцией. Если бы я должен был учитывать персонажей, как бы я это сделал?
// Calls header and menu.
int main() {
printHeading();
getMenuChoice();
}
//Prints the header.
void printHeading() {
cout << "*******************************" << endl
<< " Birthday Calculator " << endl
<< "*******************************" << endl << endl;
}
//Prints the closer.
void printCloser() {
cout << endl;
cout << "****************************************************" << endl
<< " Thanks for using the Birthday Calculator " << endl
<< "****************************************************" << endl
<< endl;
}
void printMenu() {
cout << endl << endl;
cout << "Menu Options" << endl
<< "------------" << endl;
cout << "1) Determine day of birth" << endl;
cout << "2) Print the next 10 leap years" << endl;
cout << "3) Determine birthdays for the next 10 years" << endl;
cout << "4) Finished" << endl << endl;
cout << "Choice --> ";
}
//Gets user's menu choice.
int getMenuChoice() {
int choice;
printMenu();
cin >> choice;
//If user does not select 4, it selects their menu choice.
while (choice != 4) {
if (choice == 1) {
determineDayOfBirth();
}
else if (choice == 2) {
print10LeapYears();
}
else if (choice == 3) {
print10Birthdays();
}
//User did not enter a valid choice and the following prints.
else {
cout << "Invalid menu choice" << endl;
}
//Allows the user to enter another choice
//after they have executed one choice.
printMenu();
cin >> choice;
}
//Prints closer when user chooses 4.
printCloser();
return 0;
}
Давненько я не играл с C ++, но здесь есть шанс.
int choice;
printMenu();
cin >> choice;
ValidateOption(choice);
// Then if you want them to be able to pick again you can just do it over again
printMenu();
cin >> choice;
ValidateOption(choice);
function ValidateOption(int choice){
//If user does not select 4, it selects their menu choice.
while (choice != 4) {
if (choice == 1) {
determineDayOfBirth();
}
else if (choice == 2) {
print10LeapYears();
}
else if (choice == 3) {
print10Birthdays();
}
//Prints closer when user chooses 4.
else if (choice == 4){
printCloser();
return 0;
}
//User did not enter a valid choice and the following prints.
else {
cout << "Invalid menu choice" << endl;
// Make the user select again because the input was invalid
printMenu();
cin >> choice;
}
}
}
Вы можете попробовать промыть cin
как это:
cin >> choice;
cin.clear();
cin.ignore(INT_MAX);
или как предложено @ user4581301
cin.ignore(numeric_limits<streamsize>::max(), '\n');