相关疑难解决方法(0)

为什么switch语句不能应用于字符串?

编译以下代码并得到错误type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    switch(std::string("raj"))
    {
    case"sda":
    }
}
Run Code Online (Sandbox Code Playgroud)

你不能在任何一个switch或中使用字符串case.为什么?是否有任何解决方案可以很好地支持类似于切换字符串的逻辑?

c++ string switch-statement

208
推荐指数
10
解决办法
33万
查看次数

如何根据iterable创建case语句?

我想根据迭代创建一个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++; …
Run Code Online (Sandbox Code Playgroud)

c++ loops switch-statement

2
推荐指数
1
解决办法
60
查看次数

标签 统计

c++ ×2

switch-statement ×2

loops ×1

string ×1