【发布时间】:2016-11-15 14:29:38
【问题描述】:
所以我刚刚学习了输入验证,但是我遇到了一个问题。我强迫用户输入一个数字而不是一个有效的字符串,但是如果用户输入一个数字(一个包含在开关盒中的数字)和一个字符串,那么程序就会崩溃。有关更改哪些内容以便验证适用于所有内容的任何提示?
int menu(double pi) //menu for choosing a shape
{
int choice = 0;
cout << "Please 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\n ";
while (!(cin >> choice))
{
cout << "Invalid input, please enter a number of 1-5\n\n";
cin.clear();
cin.ignore(100, '\n');
}
system("CLS");
switch (choice) //switch case for each shape
{
case 1:
circleArea(pi);
break;
case 2:
circleCircum(pi);
break;
case 3:
rectanArea();
break;
case 4:
triangArea();
break;
case 5:
cubVol();
break;
default:
cout << "Invalid input! Please try again.\n\n";
break;
}
return 0;
}
【问题讨论】:
-
通常,如果您想要防弹代码,您需要将输入作为字符串读取,然后解析并将其转换为您想要的。
-
呃,我有点明白你的意思,虽然不是很明白,如果不是问题,你介意提供一些示例代码吗?我还是个编程菜鸟,从 9 月开始
标签: c++ string validation input