从流到枚举类型的输入 [英] Input from stream to enum type
本文介绍了从流到枚举类型的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从信息流输入到枚举类型?
How to input from stream to enum type?
我可以这样做
unsigned int sex = 0;
stream >> sex;
student.m_bio.sex = static_cast<Sex>(sex);
否则?
推荐答案
inline std::istream & operator>>(std::istream & str, Sex & v) {
unsigned int sex = 0;
if (str >> sex)
v = static_cast<Sex>(sex);
return str;
}
如果要确保该值有效,这:
If you want to ensure that the value is valid, you can do something like 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;
}
这篇关于从流到枚举类型的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文