Aru*_*yan 6 c++ arrays string char switch-statement
出于某种目的,我的开关盒中需要一个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;
}
Run Code Online (Sandbox Code Playgroud)
好吧,我有点明白这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;
}
Run Code Online (Sandbox Code Playgroud)
如何使第一个代码起作用?
joh*_*ohn 12
只需使用一对额外的大括号为变量创建一个新块
case 2:
{ // <-- start new block for str
std::string str;
std::cin >> str;
break;
} // <-- end of block, str will be destroyed here
Run Code Online (Sandbox Code Playgroud)
char str[6];是默认初始化的。对于具有自动存储持续时间(“在堆栈上分配”)的简单值的 C 数组,它意味着“根本没有初始化”,所以我想这不是错误。
但是,如果像 那样初始化数组char str[6] = {},则会产生错误。
我建议您添加额外的花括号,以便str在它自己的范围内并且在进一步的case语句中不可见:
#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: { // Changed here
std::string str;
std::cin >> str;
break;
}
case 3: // `str` is not available here, no compilation error
std::cout << "World" << std:: endl;
break;
default:
std:: cout << "Whatever" << std:: endl;
}
} while(choice != 5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在哪里放置括号是样式偏好。