作者khoguan (Khoguan Phuann)
看板C_and_CPP
标题Re: [问题] enum的用法
时间Tue Jun 14 14:45:20 2005
※ 引述《wearebest (加油)》之铭言:
: enum input_name
: {
: apple=1,orange,melon,watermelon,banana,
: }thing;
banana 後面不要有逗点。
: 我对thing作列举,
: 不过我想要
: cin>>thing;
: 不过complier不给我过
: 请问是哪里有问题
因为 thing 属於 input_name 这种 enum type,
这是使用者自订的型别,标准程式库不认得,当然也没有
为它定义 cin >> 到底要丢什麽给 thing
解决办法至少有二,
一是暴力法,强制转型;
二是正规法,为 input_name 定义 operator<<
一、
cin >> (int&)thing;
缺点是无法检查输入值的范围,超出范围就可怕了。
二、
#include <iostream>
#include <stdexcept>
using namespace std;
// enum 定义见上
istream& operator>> (istream& is, input_name& inp)
{
int tmp = -1;
cin >> tmp;
if (tmp < 0 || tmp >= 8)
throw std::range_error("input out of range);
inp = static_cast<input_name>(tmp);
return is;
}
int main()
{
try {
cin >> thing;
cout << "thing==" << thing <<'\n'; //输出不用定义,会自动转成 int
}
catch (runtime_error& e)
{
cerr << e.what() << '\n';
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
※ 编辑: khoguan 来自: 220.130.208.166 (06/14 15:10)
1F:推 wearebest:谢谢 你的回答 我先研究看看^^ 59.114.139.238 06/15