Bhabes
Bhabes

Reputation: 71

Converting numbers into alphabets in 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!

Upvotes: 7

Views: 47582

Answers (5)

lingjiankong
lingjiankong

Reputation: 366

If you want to convert 0 to a, 1 to b, 2 to c ... 25 to z:

char covertedChar = (char)('a' + 2);
// Will print 'c'
cout << covertedChar;

Similary, to convert 0 to A, 1 to B, 2 to C ... 25 to Z:

char covertedChar = (char)('A' + 25);
// Will print 'Z'
cout << covertedChar;

So if you want to convert 1 to A, 2 to B, 3 to C ... 26 to Z, simply subtract 1 offset.

int toCovert = 26 // 'Z'
char covertedChar = (char)('A' + toCovert - 1);
// Will print 'Z'
cout << covertedChar;

Upvotes: 0

CashCow
CashCow

Reputation: 31445

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.

Upvotes: 10

James Kanze
James Kanze

Reputation: 153977

The simplest way would be using a table:

char
remap( int original )
{
    static char const remap[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return original >= 0 && original < sizeof(remap) - 1
        ? remap[ original ]
        : '?';   // or throw, or ...
}

Upvotes: 2

Maxim Kholyavkin
Maxim Kholyavkin

Reputation: 4573

something like that

my_print(int x)
{
    char symbol = (char)('A' + x - 1);
    cout << symbol;
}

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363717

Use an array of letters.

char nth_letter(int n)
{
    assert(n >= 1 && n <= 26)
    return "abcdefghijklmnopqrstuvwxyz"[n-1];
}

Upvotes: 30

Related Questions