2013-12-09 34 views
-1

我的代碼中有一個switch語句,如果用戶選擇1,他會被要求寫入文件寫入,如果他選擇2;他會被要求寫出要讀取的文件的名稱,但我得到這個錯誤:無法在C++中的switch語句中打開文件

'case_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; 
+0

沒問題是你不能在switch語句中聲明一個新變量 – smac89

+0

有趣的是,你向我們展示了不同的代碼。首先,你的代碼中沒有'file_name',你在你所說的警告信息中引用了它。其次,在交換機中不使用'FileName'。你想騙誰? :) – 2013-12-09 22:04:16

回答

6

把你的情況下,在大括號這樣的:

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; 
    } 
} 
+0

謝謝,我無法接受10分鐘的答案 –

+1

當你開始向案例中添加那麼多的代碼時,我會考慮把它放入一個函數中,而不是爲了可讀性。 – drescherjm

1

開關的情況下只有標籤,所以他們本身不界定範圍,你可以不在它們內部聲明變量。你必須把括號,使開關標籤內的範圍:

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"); 
} 
1

把每個案件的代碼放到它自己的函數中。這將使switch更容易閱讀以及消除這種併發症。