number to character conversion

cimon's Avatar, Join Date: Feb 2007
Go4Expert Member
int d=9;
char g;
g=d+'0';
cout<<g;

I want to know why the above works and dispalys 9;

but the one below do not display 9; although compiles fine, can't we typecast the int to char

int d=9;
char g;
g=char(d);
cout<<"kk"<<g;

thank you
0
asha's Avatar, Join Date: Nov 2006
Go4Expert Member
What does the second one display?
0
cimon's Avatar, Join Date: Feb 2007
Go4Expert Member
no it doesn't displays anything.

as if nothing is assigned to g
0
oogabooga's Avatar
Ambitious contributor
Look up the ascii codes.
'0' is 48 (decimal).
48 + 9 is 57, which is ascii for '9'.

Converting 9 to a char simply tells the system to interpret it as an ascii code.
Ascii 9 is a tab. So it actually is printing something, you just can't see it.
Try this:
cout << "(" << char(9) << ")\n";
0
cimon's Avatar, Join Date: Feb 2007
Go4Expert Member
Actually u r right that its printing tab, when I changed 9 to 38 it printed "&". Also this
cout << "(" << char(9) << ")\n"; is printing tab or & but not 9.


Why I need is number to character is , because there is a function char * getbaserep( int number , int base)

I need this number to string conversion for this above function that takes a number and return it in a particular base,

I am able to code the function, but the number its returning has to be converted to string as the return type of the function 'getbaserep' is char*.

Morover I am doing it character by character, because if the base representation calculated is 01011 . than it should actually return reverse of it 11010.

So any idea how to convet a number to string form.

thank you
0
oogabooga's Avatar
Ambitious contributor
sprintf can convert from number to string.
Can you post your function?
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Actually returning a char* isn't a good idea, because you would need to malloc the memory for it and return the pointer to it, and it's good style to malloc and free in the same function.
So it's a better idea to create the string in the calling function and pass the pointer to that string in, for the function to modify. For example: void getbaserep(int number, int base, char *output) { ... }

However as long as you remember that getbaserep() allocates memory and remember to free that memory when you don't need it any more, returning a char* is fine. It's just that kind of thing easily gets forgotten.