• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ question

quirky

Senior member
I dont understand why

//
char array[10] = "012345678";

cout << hex << int(array[0]) << dec << " " << int(array[0]);

//


prints "30 48"'

can someome please explain this to me??
 
hmm, okay but using int("0") does not produce the same outpout as int(array[0]). how come? isnt int(array[0]) identical to 0?
 
When you declare a character array, and then convert whatever is inside the array to an integer, it uses the ASCII code. For integer, the ASCII code is 48 above what it actually is. So in the case of single digit integers, just subtract 48 from what you receive when you state int(array[0]) and you should receive the correct answer.

ex:
//
char array[10] = "012345678";

cout << hex << int(array[0]) - 48 << dec << " " << int(array[0]) - 48);

//

hope this helps.
 
Originally posted by: KraziKid
When you declare a character array, and then convert whatever is inside the array to an integer, it uses the ASCII code. For integer, the ASCII code is 48 above what it actually is. So in the case of single digit integers, just subtract 48 from what you receive when you state int(array[0]) and you should receive the correct answer.

ex:
//
char array[10] = "012345678";

cout << hex << int(array[0]) - 48 << dec << " " << int(array[0]) - 48);

//

hope this helps.

yes, i understand that. and actually, its cout<<hex<<int(array[0])-30 << dec << " " << int(array[0] - 48); which would output 0 0

but what exactly does int(array[0]) mean because cout<< hex<< int(0) does not produce the same output as cout<<hex<<int(array[0])
 
First of all you are doing something that is legal, but not very smart. Try cout << int('0'); That will give you what you expect. When you convert "0" to an int, you are converting the address of the string to an int. Since "any string" is actually of type const char *. What are you getting for an output of int("0"). I bet it is a large number.
 
0 is an integer. int(0) is 0

'0' is a character. int('0') is 0x30.

"0" is a null-terminated string. int("0") gives you the address of the string "0".
 
Back
Top