看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《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)
wearebest:謝謝 你的回答 我先研究看看^^ 59.114.139.238 06/15