我知道我的方法可能有点尴尬,我正在尝试验证菜单的输入,以便只输入1-6之间的数字,并且不接受任何其他内容。我有工作代码,我把输入作为一个字符串,然后将其更改为一个int,以便在切换案例中使用它,但我知道我可以使它更有效地工作。有什么想法吗?
void menu(double pi, char ssTwo) //menu for choosing a shape
{
string choice;
cout << "Welcome to the shape calculator!\n\nPlease select what you wish to calculate:\n\n1 - Area of a Circle\n\n2 - Circumference of a Circle\n\n3 - Area of a Rectangle\n\n4 - Area of a Triangle\n\n5 - Volume of a Cuboid\n\n6 - Exit the program\n\n ";
cin >> choice;
while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5" && choice != "6")
{
cout << "Invalid input, please enter a number of 1-6\n\n";
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-5\n\n";
menu(pi, ssTwo);
break;
}
}
答案 0 :(得分:0)
将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-5\n\n";
break;
}
}
检查:http://rextester.com/WWUM1166
如果你将cin中的值读入char而不是字符串,它只会占用第一个字符;因此,如果用户按'1asdfad',您将只在char中使用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-5\n\n";
break;
}
}