2016-04-17 33 views
-2

我開發了過敏程序(請參閱下面的代碼)以記錄用戶輸入提供的過敏信息。我想添加另一個選項,讓用戶根據預定值輸入過敏的「嚴重程度」。使用類中的枚舉指定用戶輸入的值選項

我想創建一個枚舉來保存用戶應該選擇的值。這是我迄今爲止所做的,但是在枚舉方面我只是一無所知,應該如何實現。

Allergy.hpp:

#ifndef Allergy_hpp 
#define Allergy_hpp 

#include <iostream> 
#include <string> 
#include <list> 
using namespace std; 


class Allergy { 
public: 
    enum severity {mild, moderate, severe}; 

    Allergy(); 
    Allergy(string, string, list <string>); 
    ~Allergy(); 

    //getters 
    string getCategory() const; 
    string getName() const; 
    list <string> getSymptom() const; 


private: 

    string newCategory; 
    string newName; 
    list <string> newSymptom; 



}; 

#endif /* Allergy_hpp */ 

Allergy.cpp:

include "Allergy.hpp" 

Allergy::Allergy(string name, string category, list <string> symptom){ 
    newName = name; 
    newCategory = category; 
    newSymptom = symptom; 
} 

Allergy::~Allergy(){ 

} 

//getters 
string Allergy::getName() const{ 
    return newName; 
} 

string Allergy::getCategory() const{ 
    return newCategory; 
} 


list <string> Allergy::getSymptom() const{ 
    return newSymptom; 
} 

main.cpp中:

#include <iostream> 
#include <string> 
#include "Allergy.hpp" 

using namespace std; 


int main() { 
    string name; 
    string category; 
    int numSymptoms; 
    string symptHold; 
    list <string> symptom; 

    cout << "Enter allergy name: "; 
    getline(cin, name); 
    cout << "Enter allergy category: "; 
    getline(cin, category); 
    cout << "Enter number of allergy symptoms: "; 
    cin >> numSymptoms; 

    for(int i = 0; i < numSymptoms; i++){ 
     cout << "Enter symptom # " << i+1 << ": "; 
     cin >> symptHold; 
     symptom.push_back(symptHold); 
    } 

    Allergy Allergy_1(name, category, symptom); 
    cout << endl << "Allergy Name: " << Allergy_1.getName() << endl << 
    "Allergy Category: " << Allergy_1.getCategory() << endl << 
    "Allergy Symptoms: "; 

    for(auto& s : Allergy_1.getSymptom()){ 
     cout << s << ", "; 
    } 

    cout << endl; 
    return 0; 
} 

回答

1

您可以使用一個循環,並以一系列的if語句評估字符串的枚舉值。不幸的是,與某些語言不同,枚舉不會以字符串表示名稱。如何做到這一點的示例是:

enum MyEnum{ 
    Value1, 
    Value2, 
    Value3 
}; 

int main() 
{ 
    bool isParsed=false; 
    std::string line(""); 
    MyEnum myEnum; 
    std::cout<<"Please enter your selection: "; 
    while(!isParsed&&std::getline(std::cin,line)){ 
     if(line == "Value1"){ 
      isParsed = true; 
      myEnum = Value1; 
     } 
     else if(line == "Value2"){ 
      isParsed = true; 
      myEnum = Value2; 
     } 
     else if(line == "Value3"){ 
      isParsed = true; 
      myEnum = Value3; 
     }else{ 
      std::cout<<"Selection invalid, please enter a new selection: "; 
     } 
    } 
} 
+0

謝謝 - 這幫了我一把!我使用枚舉是否正確?我看到的所有例子實際上只是談論聲明,我並沒有真正看到實現。 – user1748681

+1

我會說在一般情況下,你使用枚舉是一個很好的。任何時候,如果你有一個數值列表,那麼枚舉通常是建模的好方法。 (否則,像'int嚴重性'這樣的東西,你可能會使用相當數量的_magic numbers_,這通常更好避免。) –

相關問題