int开关箱的问题
Trouble with int switch cases
因此,我生成的这个程序只能接受从1到5的数值,并且通过仅使用switch语句,我必须将该数值转换为相应的罗马数字。我在int情况下遇到了麻烦,因为我已经尝试过用数字周围的双引号,因为我确信单引号是用于字符的。我确保包含了iostream并且有int = num;
#include <iostream> //preprocessor directives are included
using namespace std;
int main() {
int num = 0;
cout << "Enter a number from 1 to 5: " << endl;
cin >> num;
switch (num) {
case "1" :
cout << "I" << endl;
break;
case "2" :
cout << "II" << endl;
break;
case "3" :
cout << "III" << endl;
break;
case "4" :
cout << "IV" << endl;
break;
case "5" :
cout << "V" << endl;
break;
}
}
您正在比较字符串值,而不是int
。去掉case
语句中的引号
您可以输入字符或字符串或任何东西来显示要输入的变量的类型!因此,将字符串作为整数输入将导致未知行为或无限循环。
对不起,没有办法告诉cin你只想要数字或从1到5的数字。
解决方案是:
使用异常处理:
#include <iostream>
int main()
{
int num = 0;
std::cin.exceptions();
try{
std::cout << "Enter a number from 1 to 5: " << std::endl;
std::cin >> num;
if(std::cin.fail())
throw "Bad input!";
if(num > 5 || num < 1)
throw "only numbers 1 throug 5 are allowed!";
}
catch(char* cp)
{
std::cout << cp << std::endl;
}
catch(...)
{
std::cout << "An error occuered sorry for the inconvenience!" << std::endl;
}
switch (num)
{
case 1 :
std::cout << "I" << std::endl;
break;
case 2 :
std::cout << "II" << std::endl;
break;
case 3 :
std::cout << "III" << std::endl;
break;
case 4 :
std::cout << "IV" << std::endl;
break;
case 5 :
std::cout << "V" << std::endl;
break;
//default:
// std::cout "Bad input! only numbers 1 through 5" << std::endl;
}
return 0;
}