无法在 C++ 中的 switch 语句中打开文件

can't open a file in switch statement in c++

本文关键字:文件 语句 switch C++ 中的      更新时间:2023-10-16

我的代码中有一个switch语句,如果用户选择1,他将被要求写入要写入的文件,如果他选择2;他会被要求写下要读取的文件名,但我得到了这个错误:

case标签跳过了"file_name"的初始化。

这是我的代码:

char FileName[100];
    char f[100];
    int choice;
    bool x;
    int idd,iddd;
    string line;
    cout<<"enter file name: "<<endl;
    cin>>FileName;
    ofstream products_out(FileName,ios::out);
    products_out<<table.p<<" "<<table.n<<" "<<table.a<<" "<<table.b<<endl;
    while(1){
    cout<<"1-add product"<<endl;
    cout<<"2-retreive product"<<endl;
    cout<<"3-update name"<<endl;
    cout<<"5-update cost"<<endl;
    cout<<"6-update quantity"<<endl;
    cout<<"4-exit"<<endl;
    cin>>choice;
    switch(choice){
    case 1:
        cout<<"enter id"<<endl;
        cin>>id;
        s.ID=id;
        cout<<"enter name"<<endl;
        cin>>name;
        strcpy(s.name,name);
        cout<<"enter cost"<<endl;
        cin>>cost;
        s.cost=cost;
        cout<<"enter quantity"<<endl;
        cin>>quantity;
        s.quantity=quantity;
        x=table.insert(s);
        products_out<<s.ID<<" "<<s.name<<" "<<s.cost<<" "<<s.quantity<<endl;
        cout<<"yes inserted"<<endl;
            break;
    case 2:
        cout<<"enter id of product"<<endl;
        cin>>idd;
        cout<<"enter the file you want to open"<<endl;
        cin>>f;
            ifstream products_in(f,ios::in);
            products_in.seekg(0, ios::beg);
            getline(products_in, line);
            if (line.find(id))
    {
        cout << endl << line;
    }

        break;

把你的箱子放在大括号里,如下所示:

case 2:
{
    cout<<"enter id of product"<<endl;
    cin>>idd;
    cout<<"enter the file you want to open"<<endl;
    cin>>f;
    ifstream products_in(f,ios::in);
    products_in.seekg(0, ios::beg);
    getline(products_in, line);
    if (line.find(id))
    {
        cout << endl << line;
    }
}

开关用例只是标签,因此它们不会自己定义作用域,并且不能在其中声明变量。你必须放上大括号才能在switch标签中创建一个范围:

case 0: 
{
    std::ofstream os("myfile"); //Ok, note the braces
}

当然,因为案例只是标签,所以您不局限于只写案例范围。你可以玩这样棘手的游戏:

case 0: 
{
    std::ofstream ok_file("myfile"); //Ok, note the braces
case 1:
...
case 10:
}
default:
{
    std::ofstream error_file("other file");
}

将每个案例的代码放入其自己的函数中。这将使switch更容易阅读,并消除这种复杂性。