Question about enum
Dec 8, 2013 at 3:36am UTC
Hi all!
Ok, so let's say I have this enum:
1 2
enum letters {A, B, C, D, E, F};
letters l;
and I ask the user to choose a letter and he types D.
I know D has the value 3 but how can I get the number?
something like:
but where's D I want the letter the user chose and x equals to the value corresponding to that letter in the enum.
Or maybe enums aren't the best for this situation?
Last edited on Dec 8, 2013 at 3:45am UTC
Dec 8, 2013 at 4:01am UTC
using enums would be fine. The code you presented would make the value stored in x a 3. Which is what it sounds like you want.
Dec 8, 2013 at 1:09pm UTC
dmpaul26, not really. here's a more complete example of what I really want:
1 2 3 4 5 6 7 8
enum letters {A, DD, CON, D, HELP, FIRE}; // just an example
int x;
string s;
cout << "Choose a code!" ;
cin >> s //user typed D
x = .... // now what?
I can't put x = stoi(s) because that would just convert the string into a int. I wanted to check if the s is in the enum and return the value associated to it (in this case, 3).
Last edited on Dec 8, 2013 at 1:10pm UTC
Dec 8, 2013 at 1:15pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <cctype>
enum letter { A, B, C, D, E, INVALID = -1 };
std::istream& operator >> ( std::istream& stm, letter& opt )
{
char c ;
stm >> c ;
switch ( std::toupper(c) )
{
case 'A' : opt = A ; break ;
case 'B' : opt = B ; break ;
case 'C' : opt = C ; break ;
case 'D' : opt = D ; break ;
case 'E' : opt = E ; break ;
default : opt = INVALID ;
}
return stm ;
}
int main()
{
letter choice ;
std::cout << "choice [A-E]? " ;
std::cin >> choice ;
// ...
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <string>
enum colour_t { BLACK, RED, GREEN, BLUE, WHITE, INVALID = -1 };
std::istream& operator >> ( std::istream& stm, colour_t& clr )
{
std::string str ;
stm >> str ;
if ( str == "BLACK" ) clr = BLACK ;
else if ( str == "RED" ) clr = RED ;
else if ( str == "GREEN" ) clr = GREEN ;
else if ( str == "BLUE" ) clr = BLUE ;
else if ( str == "WHITE" ) clr = WHITE ;
else clr = INVALID ;
return stm ;
}
int main()
{
colour_t clr ;
std::cout << "colour [BLACK, RED, GREEN, BLUE, WHITE]? " ;
std::cin >> clr ;
}
Last edited on Dec 8, 2013 at 1:24pm UTC
Topic archived. No new replies allowed.