我知道我的方法可能有点尴尬,我正在尝试验证菜单的输入,以便输入1-6之间的数字,而没有其他任何东西。我有工作代码,在其中将输入作为字符串进行输入,然后将其更改为INT以便在开关情况下使用它,但是我知道我可以使其更有效地工作。有什么想法吗?
void menu(double pi, char ssTwo) //menu for choosing a shape
{
string choice;
cout << "Welcome to the shape calculator!nnPlease select what you wish to calculate:nn1 - Area of a Circlenn2 - Circumference of a Circlenn3 - Area of a Rectanglenn4 - Area of a Trianglenn5 - Volume of a Cuboidnn6 - Exit the programnn ";
cin >> choice;
while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5" && choice != "6")
{
cout << "Invalid input, please enter a number of 1-6nn";
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
int choiceInt = atoi(choice.c_str());
system("CLS");
switch (choiceInt) //switch case for each shape
{
case 1:
circleArea(pi, ssTwo);
break;
case 2:
circleCircum(pi, ssTwo);
break;
case 3:
rectanArea(ssTwo);
break;
case 4:
triangArea(ssTwo);
break;
case 5:
cubVol();
break;
case 6:
exitSystem();
break;
default:
cout << "Invalid input, please enter a number of 1-5nn";
menu(pi, ssTwo);
break;
}
}
将char视为ASCII值;检查http://rextester.com/xkmj90988
#define ONE 49
#define TWO 50
int main()
{
char val = '1';
switch (val)
{
case ONE:
{
std::cout << "1 was Selected";
break;
}
case TWO :
{
std::cout << "2 was Selected";
break;
}
default:
std::cout << "Invalid input, please enter a number of 1-5nn";
break;
}
}
更新#1
检查:http://rextester.com/wwum1166
,如果您将CIN的值读取到字符中而不是字符串,它只会采用第一个字符;因此,如果用户按" 1ASDFAD",您将只有1个字符,并且将使用1个;如果按下" asdfasdf",它将读取" a",并显示无效的输入;
int main()
{
char val;
std::cout << "Enter a number: ";
std::cin >> val;
std::cout << val << "n";
switch (val)
{
case '1':
{
std::cout << "1 was Selected";
break;
}
case '2':
{
std::cout << "2 was Selected";
break;
}
default:
std::cout << "Invalid input, please enter a number of 1-5nn";
break;
}
}