Turning a int into a char

Hi everybody. I am making a code where it compares two different char, the problem is that one of the variables is a int and not a char.

I tried some different things, but the best I ever got was weird signs instead of numbers.

The value that is to be turned into a char is "ia", that is the name. Has anyone got any suggestions?

Thanks,
Nicolai
"ia" are 2 characters (to be precise 3 because of the string-termination-character)
1 character can't hold that much information, I'm sorry.
This is all you need to understand the difference between int and char:
http://www.asciitable.com/

In other words,
1
2
3
int num = 0;
// Is the same as 
char c = 48; // or char c = '0'; 


You can refer to a char by its ASCII value, which is an int, but as Gamer pointed out, that value can only represent one character.
char c = '10'; // will overflow and return c == 0, for example

char c = 10; // will return c == \n, maybe?

Consider this:

1
2
3
4
5
int i = 105;
char c = 'a';

cout << "The character that 'i' refers to is equal to " << (char)i << " or " << i <<  '\n';
cout << "The character that 'c' refers to is equal to " << c << " or " << (int)c <<  '\n';


The character that 'i' refers to is equal to i or 105
The character that 'c' refers to is equal to a or 97


<edit>
"ia", with double quotes is a string. You can loop through the string and combine the integer values, for example:

1
2
3
4
5
6
7
string str = "ai";
int num = 0;

for(int i = 0; i < str.length(); i++)
	num += str.at(i);

cout << num << '\n';


202


You can, of course, do many other similar conversions depending on what you want to do.
Last edited on
Hi Gamer2015 and admkrk.

First off, I just realised there has been some confusion about the question. Obviously you can't have a int containing non-Numeric material. What I ment was my int containing a single digit is named "ai".

I guess from admkrk answer, I could use the table to then convert it in, by adding a number? So int ai = 0
char newAi = ai + 48?

Thanks for your very informative answer admkrk. This actually changes my view on char. I though it was simple a string only containing a single number or letter.
A string does contain numbers or letters. It is an array of one, or the other, or even both. Each element, or index is a single char. So, ['a']['i'] == [97][105].

Because the ASCII table allows you to interchange values, you can do things like:
1
2
if('A' < 'a')
    cout << "This is the same as, if(65 < 97)" << '\n';

without casting to integers.

You just have to remember that a char is a single element (0-9 || a-z || A-Z), while it's ASCII value can be 0-127.
Topic archived. No new replies allowed.