I have an enum in my code that is the following: enum Status {In-Active, Active};
.
A status object is passed to a Person
object as a parameter, so I wa
You can't read enum
values directly, you'll need a std::map
that maps user input to an enum
value.
std::map<std::string,Status> m;
m["In-Active"] = In-Active;
m["Active"] = Active;
std::string sstatus;
cin >> sstatus;
Status status = m[sstatus];
Enum objects are being parsed at compile time and it can only contain constant integer values.
Person p(name, age, status); //Here without using status object you should send a value directly like "In-Active" or "Active". So there would be no input from the user regarding th status field.
enum Status {InActive, Active};
Status status;
cout << "Enter status: "; cin >> status;
You can also wrap the enum inside a class and provide operator>>. This is a modified example from this link http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Type_Safe_Enum
#include <iostream>
template<typename def>
class safe_enum : public def
{
public:
int val;
safe_enum(int v) : val(v) {}
// inner underlying() const { return val; }
bool operator == (const safe_enum & s) const { return this->val == s.val; }
bool operator != (const safe_enum & s) const { return this->val != s.val; }
bool operator < (const safe_enum & s) const { return this->val < s.val; }
bool operator <= (const safe_enum & s) const { return this->val <= s.val; }
bool operator > (const safe_enum & s) const { return this->val > s.val; }
bool operator >= (const safe_enum & s) const { return this->val >= s.val; }
};
struct status_def {
enum type { NoValue, InActive, Active };
};
typedef safe_enum<status_def> Status;
std::istream& operator>>(std::istream& Istr, Status& other)
{
std::cout << "Enter Status value: " << std::endl;
//here the logic to handle input error
Istr >> other.val;
return Istr;
}
std::ostream& operator<<(std::ostream& os,const Status& toPrint)
{
if (toPrint.val == Status::Active)
return os << "Active";
if (toPrint.val == Status::NoValue)
return os << "NoValue";
if (toPrint.val == Status::InActive)
return os << "InActive";
throw;
}
int main(void)
{
Status test(Status::NoValue);
std::cout << test << std::endl;
std::cin >> test;
std::cout << test << std::endl;
}