【发布时间】:2020-08-25 17:29:30
【问题描述】:
出于某种目的,我的开关盒中需要一个std:: vector<char> 或std:: string。因此,我编写了以下虚拟代码以查看它是否有效:
#include <iostream>
#include <string>
int main() {
int choice = 0;
do {
std:: cout << "Enter Choice" << std::endl;
std:: cin >> choice;
switch(choice) {
case 1:
std::cout << "Hi";
break;
case 2:
std::string str;
std::cin >> str;
break;
case 3: //Compilation error, Cannot jump from switch statement to this case label
std::cout << "World" << std:: endl;
break;
default:
std:: cout << "Whatever" << std:: endl;
}
} while(choice != 5);
return 0;
}
好的,我知道str 是std:: string 类型的对象。所以,我试图跳过这个变量初始化。
那为什么定义C风格的字符串不会导致编译错误:
#include <iostream>
#include <string>
int main() {
int choice = 0;
do {
std:: cout << "Enter Choice" << std::endl;
std:: cin >> choice;
switch(choice) {
case 1:
std::cout << "Hi";
break;
case 2:
char str[6];
std::cin >> str;
break;
case 3:
std::cout << "World" << std:: endl;
break;
default:
std:: cout << "Whatever" << std:: endl;
}
} while(choice != 5);
return 0;
}
我怎样才能使第一个代码工作?
【问题讨论】:
标签: c++ arrays string char switch-statement