Something like this:

#include<iostream>
using namespace std;
 
// the function below takes an integer and outputs a corresponding letter
void convert (int num) 
{
   ...   
 
}
 
int main
{
   int num;
   cout << "Enter an integer" << endl;
   cin >> num;
   convert (num); 
 
   system("pause");
   return 0;
}

E.g.
Input: 0 , Output: "A''
Input: 1 , Output: "B''
Input: 25 , Output: "Z''
Input: 26 , Output: "A'' (repeats the alphabet again)
Input: 2033, Output: ''F''

I've thought of using a switch in the function convert but of course there are too many integers ):
So what approach can I use? I'd rather not use arrays I haven't learnt them yet.

Recommended Answers

All 3 Replies

Take advantage of the fact that characters are represented by integer values on your computer, and therefore may be added to other integer types.

char convert(int i)
{
    return (i%26) + 'A';
}

EDIT: Note - This depends on the character set on your computer having the letters 'A'..'Z' as a contiguous set. As far as I am aware, most character sets do (such as ASCII), but there is always a possibility that some obscure character set somewhere in the world doesn't.


EDIT2: For the more portable solution using the <string> library

char convert(int i)
{
    std::string s("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    return s.at( i % s.size() );
}

See EBCDIC for an example of a character set that doesn't have consecutive A..Z.

Ah ok thanks very much for that. First I thought adding an integer to "A" wasn't possible but then I saw that only single quotation marks were used. So initializing any variable of type char requires single quotation marks? I'm sorry as I've only used numbers before.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.