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

标签 c++ loops switch-statement

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

相关文章:

c++ - .cpp 文件中的虚拟 C++ 方法实现是否应该标记为虚拟?

c++ - 结构上的 std::replace_if

c++ - 无法配置文件

python - 在 for 循环中引用 Python 可迭代项的相邻项

php - 使用 PHP 根据 URI 更改 href

android - 使用MediaRecorder android时如何在前后摄像头之间切换

C++ 编码指南 102

python - 循环中的简单逻辑解释?

r - 循环和引导脚本运行时间过长

javascript - Javascript 中字符串的 Switch-Case 未按预期工作