Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   number to character conversion (http://www.go4expert.com/forums/character-conversion-t14592/)

cimon 17Oct2008 06:55

number to character conversion
 
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

asha 17Oct2008 10:32

Re: number to character conversion
 
What does the second one display?

cimon 17Oct2008 12:27

Re: number to character conversion
 
no it doesn't displays anything.

as if nothing is assigned to g

oogabooga 17Oct2008 21:52

Re: number to character conversion
 
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";

cimon 17Oct2008 22:07

Re: number to character conversion
 
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

oogabooga 18Oct2008 01:15

Re: number to character conversion
 
sprintf can convert from number to string.
Can you post your function?

xpi0t0s 18Oct2008 02:37

Re: number to character conversion
 
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.


All times are GMT +5.5. The time now is 16:28.