我有这个程序
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?
使用 if
和 else
:
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/