c++ - 开关量不是整数

标签 c++ switch-statement

我有这个程序

int main()
{
    string valami = "-- .- .-. -.- ------ -- .- .-. -.-";
    from_morse_string(valami);
    return 0;
}

int from_morse_string(string input_morse_string)
{
    string morse_arr[1764];

    int j = 0;
    stringstream ssin(input_morse_string);
    while (ssin.good() && j < 1764)
    {
        ssin >> morse_arr[j];
        ++j;
    }

    for(int i = 0; i < j; i++)
    {
        switch(morse_arr[i])
        {
            case ".-" : cout << "a" << endl; break;
            case "-..." : cout << "b" << endl; break;
            case "-.-." : cout << "c" << endl; break;
            ...
            case "----." : cout << 9 << endl; break;
            case "-----" : cout << 0 << endl; break;
            default : cout << "it's contain invalid morse code";
        }
    }
    return 0;
}

这是一个简单的摩尔斯电码解码器,一个非常非常简单的程序,但是当我想运行时,我收到这个错误消息:“switch quantity not an integer”

有什么问题?我该如何解决?

最佳答案

What's the problem?

如错误所述,您只能将 switch 与整数一起使用,而不是字符串。

How can i solve it?

使用 ifelse:

if (morse_arr[i] == ".-") {
    cout << "a" << endl;
} else if (morse_arr[i] == "-...") {
    cout << "b" << endl;
} // and so on

或使用查找表

std::map<std::string, char> morse_map = {
    {".-", 'a'},
    {"-...", 'b'},
    // and so on
};

auto found = morse_map.find(morse_arr[i]);
if (found == morse_map.end()) {
    cout << "invalid morse code\n";
} else {
    cout << found->second << endl;
}

关于c++ - 开关量不是整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20430865/

相关文章:

c++ - WinMain/Win32 窗口不显示,但显示在任务管理器的进程选项卡中

c++ - 关于 pragma Ident 的问题

c - C中使用switch语句的疑惑

C++:数组元素设置为 0

c++ - perf 输出中的奇怪字符...

c++ - 以 sizeof ... (args) == 0 作为基本情况的参数包的函数无法编译

c++ - 整数的模数

java - 如何减少 if 语句

c++ - 在 C switch/case 中声明变量

c# - 如何将所有案例合并为一个?