gpt4 book ai didi

c++ - 我如何根据可迭代对象进行案例陈述?

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:48 26 4
gpt4 key购买 nike

我想基于可迭代对象做一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com