我想基于可迭代对象做一个 case 语句,但我知道 case 表达式必须是一个常量。有什么解决方法?
我试了下面的代码,还是不行。
#include <iostream>
using std::cout;
using namespace std;
int main()
{
int i = 0;
while( i >= 0)
{
const int z = i;
cout << "Enter a number other than " << z << "!\n";
int choice;
cin >> choice;
switch(choice){
case z: cout << "Hey! you weren't supposed to enter "<< z <<"!"; return 0; break;
default: if(i==10)
{
cout << "Wow, you're more patient then I am, you win."; return 0;
}
break;
}
i++;
}
}
最佳答案
case
需要在编译时已知的常数整数值。
所以你必须使用if
-s:
if (choice == z) {
cout << "Hey! you weren't supposed to enter "<< z <<"!";
return 0;
} else if (i == 10) {
cout << "Wow, you're more patient then I am, you win.";
return 0;
}
关于c++ - 我如何根据可迭代对象进行案例陈述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46832306/