0

I'm going mad trying to figure this out but nothing I try is working. Please help me out here.

char ch[5];
int in = 15;
ch[2] = in; // It has to be on a specefic place in that array
cout << ch[2]; // Prints '*'

I know i can do something like ch[2] = in+48; but that will only work with numbers smaller than 10.

3
  • int is bigger than char. Are you trying to truncate the int value to the size of a char, or split the int up into multiple char's? Commented Jan 17, 2014 at 17:15
  • You can't. What that does is type-cast the integer to a char, which basically chops off the high bits and only leaves the eight low bits which happens to be the same value as the ASCII code for '*'. Commented Jan 17, 2014 at 17:15
  • 1
    What are you expecting cout to print? 15? Commented Jan 17, 2014 at 17:32

1 Answer 1

1

When cout receives a char, it interprets it as a character (according to the execution character set) rather than just an integer value. If you want to print the integer value, you'll need to cast it to some other integer type:

cout << static_cast<int>(ch[2]);

Note that you will almost certainly not be able to store all the values of an int in a char. If your char is 8 bits (which it probably is), then 255 is the maximum value you can store in it.

Sign up to request clarification or add additional context in comments.

4 Comments

@LightnessRacesinOrbit Interesting.. what exactly happened here?
@LightnessRacesinOrbit I prefer the cast because it expresses intention.
@Digital_Reality: Unary + results in integral promotion.
@sftrabbit: Me too ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.