Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting numbers into alphabets in c++

Tags:

c++

I'm trying to write a code that would convert numbers into alphabets. For example 1 will be 'A', 2 will be 'B', 3 will be 'C' and so on. Im thinking of writing 26 if statements. I'm wondering if there's a better way to do this...

Thank you!

like image 885
Bhabes Avatar asked Feb 13 '12 10:02

Bhabes


2 Answers

Use an array of letters.

char nth_letter(int n)
{
    assert(n >= 1 && n <= 26)
    return "abcdefghijklmnopqrstuvwxyz"[n-1];
}
like image 97
Fred Foo Avatar answered Sep 21 '22 04:09

Fred Foo


If you can rely on the using an ASCII character set where they are consecutive then you can convert

char intToAlphabet( int i )
{
   return static_cast<char>('A' - 1 + i);
}

If you can sometimes rely on this fact, e.g. you can set a compiler flag or similar for the particular target, you can also use this code for that specific build.

Otherwise use a static lookup table (as others have suggested).

Note that it is preferable to "assert" your range check if your numbered input comes from program variables that you know should never be out of range.

If the input comes from user-provided data where the users could potentially provide rogue data, you need a way to handle it that is not "undefined behaviour". Therefore you would have to check each value and either throw an exception (informing the user to correct their data) or use some character to indicate a bad input.

like image 29
CashCow Avatar answered Sep 19 '22 04:09

CashCow