c++ - Input from stream to enum type -
how input stream enum type?
i can so
unsigned int sex = 0; stream >> sex; student.m_bio.sex = static_cast<sex>(sex); otherwise?
inline std::istream & operator>>(std::istream & str, sex & v) { unsigned int sex = 0; if (str >> sex) v = static_cast<sex>(sex); return str; } if want ensure value valid, can this:
enum sex { male, female, sex_count }; inline std::istream & operator>>(std::istream & str, sex & v) { unsigned int sex = 0; if (!(str >> sex)) return str; if (sex >= sex_count) { str.setstate(str.rdstate() | std::ios::failbit); return str; } v = static_cast<sex>(sex); return str; }
Comments
Post a Comment