跳转跳过switch语句中的变量初始化

问题描述 投票:0回答:1

出于某种目的,我在开关盒中需要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;
}

[确定,我有点理解strstd:: 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
1个回答
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;
    ....
© www.soinside.com 2019 - 2024. All rights reserved.