出于某种目的,我在开关盒中需要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;
}
如何使第一个代码起作用?
您必须将变量声明移到switch语句的前面:
...
do {
std::cout << "Enter Choice" << std::endl;
std::cin >> choice;
std::string str; <<<<<<<<<<<<<<<<<<<<<<<
switch(choice) {
case 1:
std::cout << "Hi";
break;
case 2:
std::cin >> str;
break;
....