2012-11-20 77 views
3

我寫了一個關於如何在class中訪問我的字段的特定方法,但是我的老師告訴我應該使用enum在enum中編寫代碼

如何重新編寫此代碼以使用enum而不是使用goto

void SetType() { 
    cout << "Book SetType" << endl; 
    Choice: cout << "Please Select from the list: \n " 
      << "1- Technical literature \n " 
      << "2- Fiction literature \n " 
      << "3- Textbook" << endl; 
    int i; 
    cin >> i; 

    switch (i) { 
    case 1: 
     Type = "Technical literature"; 
     break; 
    case 2: 
     Type = "Fiction literature"; 
     break; 
    case 3: 
     Type = "Textbook"; 
     break; 
    default: 
     cout << "Erorr you entered a wrong choice" << endl; 
     goto Choice; 
    } 
} 
+0

想一想枚舉的實際類型是什麼,以及它將在您顯示的代碼中替換什麼。 –

+1

你也想檢查你是否成功讀取任何東西:'if(std :: cin >> i){...}' –

+0

你的老師意味着你應該枚舉值而不是'魔術'數字。你可以避免goto循環,因爲 – Lol4t0

回答

4

只是使用循環,而不是它的gotos將是一個意大利麪代碼。 枚舉很好,不關心定義的數字,因爲如果添加一個新的定義,它們會自動增加。

#include <iostream> 
#include <string> 
void SetType(); 

using namespace std; 
string Type; 
int main() 
{ 
    SetType(); 

    cout << "so you choose " << Type << endl; 
    return 0; 
} 
enum select 
{ 
    Technical_literature = 1, 
    Fiction_literature, 
    Textbook 
}; 

void SetType() { 
    cout<<"Book SetType"<<endl; 
    while(1) 
    { 
     cout<<"Please Select from the list: \n 1- Technical literature \n 2- Fiction literature \n 3- Textbook"<<endl; 
     int i; 
     cin >> i; 

     switch(i) { 
     case Technical_literature: 
      Type="Technical literature"; 
      return; 
     case Fiction_literature: 
      Type="Fiction literature"; 
      return; 
     case Textbook: 
      Type="Textbook"; 
      return; 
     default: 
      cout << "Erorr you entered a wrong choice" << endl; 

     } 
    } 
} 
+1

這解釋了OP的兩個隱含的2個問題**。 –

+0

突破,而不是返回案例教科書:'... – PiotrNycz

1

你的老師的意思是,而不是硬編碼常量在所有地方,你需要聲明你我作爲枚舉。

enum some_type { 
    type_techlit=1, type_fiction, type_textbook 
}; 

some_type i; 

然後閱讀枚舉。