enum Type { A=1, B, C };
If I request through cin>>
number, then how can I list an element of an enumeration using this number? For example I entered 2, I printed B
Searched in Google, did not find ... all examples for C #
enum Type { A=1, B, C };
If I request through cin>>
number, then how can I list an element of an enumeration using this number? For example I entered 2, I printed B
Searched in Google, did not find ... all examples for C #
Good day! The answer to your question depends on what you want to receive. If you want to get the name of an enumeration item, then you need to overload the input / output statements to the stream. I learned this technique from the book by B. Straustrup "Design and Evolution of C ++" (I strongly advise you to read it - you can learn a lot from this). If you just want to know the element of the enumeration itself, then use static_cast
to safely cast.
#include <iostream> #include <string> #include <stdexcept> enum Type { A = 0, B, C }; std::ostream& operator << (std::ostream& out, const Type& t) { switch(t) { case A: return (out << "A"); case B: return (out << "B"); case C: return (out << "C"); } return (out); } std::istream& operator >> (std::istream& input, Type& t) { std::string s; input >> s; if (s == "A") { // неявная конвертация в Type t = A; } else if (s == "B") { t = B; } else if (s == "C") { t = C; } else { // здесь можно выкинуть исключение throw std::runtime_error("incorrect input"); } return (input); } int main(int argc, char *argv[]) { using namespace std; Type type; try { cin >> type; } catch(std::exception& e) { cout << e.what(); return 1; } cout << type << "=" << static_cast<int>(type); return 0; }
The variant with an associative array also has a right to exist, but one has to pay with memory overruns, and additionally, transfers usually rarely change, so it will not be difficult to insert a couple of lines later.
Well, for example, it was possible to google for the query "c ++ enum to string" and good Google would give you the very first result of this. Some simple witchcraft on your part, and everything works
Look for char *, likewise for int
enum ex {A, B, C, NONE}; struct enex { ex en; const char *name; }; static ex get_enum (const char *name) { static struct enex en[] = {{A,"A"},{B,"B"},{C,"C"},{A,0}}; for (int i = 0; en[i].name; i++) if (strcmp(name,en[i].name) == 0) return en[i].en; return NONE; }
cin >>
) I misunderstood the question. I decided that it was required to return enum by the entered numerical value, but wrote a return for the entered name . In general, the comparison between enum and int compiler (g ++) permits, so for numeric values you can simply search the integer in the array of enums and return the enum. But, it is somehow ugly ("dumb"). - avpSource: https://ru.stackoverflow.com/questions/204871/
All Articles
С++
this behavior is not provided. You might as well ask: "how to type the name of a variable whose address the pointer stores." - megamap
- skegg