我开发了过敏程序(见下面的代码)来记录用户输入提供的过敏信息。我想为用户添加另一个选项,根据预定值输入过敏症的“严重程度”。
我想创建一个枚举来保存用户应该选择的值。这是我到目前为止所做的,但是当我谈到枚举以及它应该如何实现时,我只是无知。
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;
}
答案 0 :(得分:1)
您可以使用循环和一系列if语句来评估字符串中的枚举值。不幸的是,不像某种语言,enum不会附带他们名字的字符串表示。如何执行此操作的示例将是:
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: ";
}
}
}