跨越字符串的初始化并跳转到标签大小写

Not*_*Pr0 3 c++ menu switch-statement

我正在尝试为我的程序做案例菜单。我总是收到交叉初始化错误,我以前从未见过这个错误。也许有人可以向我解释我的代码出了什么问题。

#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <fstream>

using namespace std;

#define N_CARS 1

struct car{
    string model;
    int year;
    double price;
    bool available;
}cars [N_CARS];


void menu();
void mainMenu();

void writeToFile(ofstream &outputFile , const car& p)
{
    outputFile << p.model << " "
               << p.year << " "
               << p.price << " "
               << p.available<<"\n";
}

int choice1 = 0;


int main(int argc, char** argv) {

    menu();
    return 0;
}


void menu() {

    do {
        mainMenu();

        switch(choice1) {

            case 1:
                string mystr;
                string mystr2;
                string mystr3;

                int n;
                for (n=0; n<N_CARS; n++)
                {
                    cout << "Enter title: ";
                    getline (cin,cars[n].model);
                    cout << "Enter year: ";
                    getline (cin,mystr);
                    stringstream(mystr) >> cars[n].year;
                    cout << "Enter price: ";
                    getline (cin,mystr2);
                    stringstream(mystr2) >> cars[n].price;
                    cout << "Choose availability: ";
                    getline (cin,mystr3);
                    stringstream(mystr3) >> cars[n].available;
                }

                ofstream outputFile;
                outputFile.open("bla.txt", fstream::app);
                for (n=0; n<N_CARS; n++)
                    writeToFile(outputFile, cars[n]);
                outputFile.close();
                break;

            case 2:
                break;

            case 5:
                break;
        }

    } while(choice1 != 5);

}


void mainMenu(void) {

    cout << "Main Menu\n";
    cout << "1 - Enter Car\n";
    cout << "5 - Quit\n";
    cout << "Please choose: ";

    cin >> choice1;
}
Run Code Online (Sandbox Code Playgroud)

错误:

In function 'void menu()':
    [Error] jump to case label [-fpermissive]
    [Error] crosses initialization of 'std::ofstream outputFile'
    [Error] crosses initialization of 'std::string mystr3'
    [Error] crosses initialization of 'std::string mystr2'
    [Error] crosses initialization of 'std::string mystr'
Run Code Online (Sandbox Code Playgroud)

Chr*_*ckl 5

case标签实际上很像可怕的goto标签;它们不构成新的范围。因此,无论好坏,switch选择要跳转到的正确case标签很像goto跳转到标签的语句。跳转不允许跨越各种对象的初始化 - 正如错误消息所述。

对你来说最干净的事情就是剪切case 1:和之间的所有内容break; case 2:并将其粘贴到一个名为 之类的新函数enterCar中。

void enterCar() {
    // code previously found between the case labels
}

// ...
switch(choice1) {
    case 1: enterCar(); break;
    case 2:
    // ...
}
Run Code Online (Sandbox Code Playgroud)

函数构成了一个新的作用域,您的本地对象可以在其中正确初始化。作为奖励,您正在迈出第一步,将所有意大利面条代码抛在脑后。