Home > OS >  c enum characher from integer value
c enum characher from integer value

Time:12-08

So my problem goes like this, i have to enter a number from 1-7 and for each respective number i have to print a letter from the word english(e is for 1, n is for 2, etc.) Here is my idea:

#include <iostream>
using namespace std;
int main()
{
    enum eng {e='e', n='n',g,l,i,s,h} 
    };
    int x;
    cout << "dati x\n"; 
    cin >> x;
    if (x >= 0 && x <= 7)
        eng val = static_cast<eng>(x);
        cout << x;

    
}

i want the number ( x ) to be converted to its respective letter from the eng type, but the conversion gives me back the number( if i put 1 it gives me 1, if i put 2 it gives me 2) i tried assigning an char value to e and n in eng , to see what happens ,but its the same result, i know i can use switch,but i want to try to get this working

CodePudding user response:

The enum you have doesn't have values 0, 1, ... because you set 'e' and 'n'. These are chars and have int values of 101 and 110 respectively. all the enum values after 'n' will be incremented by 1 starting from 110. What you want, as said, is a const array of some sort(std::array, char[], std::vector) where you add the chars 'e', 'n', ... to this array. You can then just use myArray[0-6] to get the according char.

CodePudding user response:

Discussing enums is somewhat beyond the scope of the question, because an enum is just the wrong tool here. The values of the letters in the word "english" are not consecutive and the names of an enums named constants are not easily accessible, hence the enum does not help to map an index to a character.

The tool to map an index to a character is a std::string:

 std::string english{"english"};
 if (x >= 1 && x < 8) std::cout << english[x-1];

Your bounds were wrong. "english" has only 7 characters, while your condition allows 8 different indices. Because array indexing is zero based but the taks asks you to use 1 based indexing, you need to subtract 1 to get the desired character. Moreover, its a matter of style, but it is common to use half open intervals (ie [1,8), lower bound included, upper bound not included).

  • Related