PDA

View Full Version : How to convert int to char?



leon.vitanos
December 22nd, 2010, 07:33 PM
I have an integer and I want to convert it into char but keeping its value!! !!!
How to do that?

trent.josephsen
December 22nd, 2010, 07:37 PM
What?

leon.vitanos
December 22nd, 2010, 07:41 PM
What?

I changed the question...:D:D:D

PaulM1985
December 22nd, 2010, 07:43 PM
Any particular programming language?

leon.vitanos
December 22nd, 2010, 07:48 PM
Any particular programming language?

Yes..Sorry C++

hakermania
December 22nd, 2010, 07:52 PM
So, you want e.g.

int a = 57
to be converted into

char b = "57"
?

PaulM1985
December 22nd, 2010, 07:53 PM
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

First link on "convert int to char c++" on google.

dwhitney67
December 22nd, 2010, 08:22 PM
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

First link on "convert int to char c++" on google.

Oh no, Mr Bill!... that function is non-standard.

If we take the OP literally at his word, then technically only int values ranging from -128 to 127 can be converted to a char; if converting to an unsigned char, then values 0 through 255 can be used.

If the OP meant how to convert an int to an array of chars (aka a string), then the easiest and most portable C++ way is to use the std::stringstream.



int value = 12345;
std::stringstream ss;

ss << value;

std::cout << "As a string: " << ss.str() << std::endl;

PaulM1985
December 22nd, 2010, 09:33 PM
Oh no, Mr Bill!... that function is non-standard.

If we take the OP literally at his word, then technically only int values ranging from -128 to 127 can be converted to a char; if converting to an unsigned char, then values 0 through 255 can be used.

If the OP meant how to convert an int to an array of chars (aka a string), then the easiest and most portable C++ way is to use the std::stringstream.



int value = 12345;
std::stringstream ss;

ss << value;

std::cout << "As a string: " << ss.str() << std::endl;


Yep, I should have thought of that. I let a bad day at work get the better of me.

Sorry peeps. More specifically sorry Bong.Da.City

Paul

worksofcraft
December 22nd, 2010, 10:48 PM
OTOH if you want it to be localizable to Hindu-Arabic numerals with a Duodecimal number base to be rendered right to left then you might need something a bit more flexible than stringstream :D

It's a good thing I completed my C++international numeric formatting library (http://code.google.com/p/speaknumber/downloads/list) for cases like this :D