convert int to char

Oct 19, 2011 at 3:53pm
i just want to convert in to char so i can display it in button
Oct 19, 2011 at 4:14pm
There's itoa, which is non-standard.

There's also this option, using stringstream

1
2
3
4
5
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();



giving you a string version of the number. Did you really want a single char, like this?
char c = s[0];

or did you mean a char pointer, like this:
char* c = s.c_str();
Last edited on Oct 19, 2011 at 4:16pm
Oct 19, 2011 at 5:07pm
1
2
3
int n = ...
if( 0 <= n && n <= 9 )
    char c = '0' + n;
Oct 19, 2011 at 11:16pm
Do not use stringstream, that isn't the proper use for it, ostringstream is. ostringsteam is one way where stringstream is two way.

1
2
3
int i = 5;
std::ostringstream o;
o << i;


Then you can use this next code anywhere you need to place a char * instead of the integer.

 
o.str().c_str();


You can put it into a string like above but I try to avoid using variables unless I need them because that is more space your program will need for memory. But if you want a string variable to hold it, here you go.

 
std::string s = o.str();


stringstream is great when you have data going both ways but you should use ostringstream and istringstream if you only intend to go one way with the data.

By the way, you need to include <sstream> into your program to use any of these 3 streams.
Last edited on Oct 19, 2011 at 11:17pm
Topic archived. No new replies allowed.