How to cast an int variable to char in C++?
char a[3];
int x=9;
int y=8;
a[0]=(char)x;
a[1]=(char)y;
a[2]='\0';
unsigned char * temp=(unsigned char*)a开发者_StackOverflow中文版;
but when i am displaying this temp, it's displaying ?8. should display 98.
can anyone please help???
char a[3];
int x='9';
int y='8';
a[0]=(char)x;
a[1]=(char)y;
a[2]='\0';
unsigned char * temp=(unsigned char*)a;
printf("%s", temp);
You were giving a value of 9 and 8, instead of their ASCII values.
Try using itoa or sprintf
Event better, given that you are using C++ try using stringstream. You can then do it as follows
std::stringstream stream;
stream << x << y;
Or, more generic
template <class T> string toString (const T& obj)
{
stringstream ss;
ss << obj;
return ss.str();
}
Something like nico's solution is what you should be using (also see boost::lexical_cast if you have boost), but for a direct answer to your question (if you want to understand things at a lower level, e.g.), the string [9, 8, \0] is not "98".
"98" is actually [57, 56, 0] or [0x39, 0x38, 0x0] in ASCII. If you want to concatenate decimal numbers ranging from 0 to 9 this way manually, you'll have to add '0' (0x30) to them. If you want to deal with numbers exceeding that range, you'll have to do more work to extract each digit. Overall, you should use something like the toString function template nico posted or boost::lexical_cast for a more complete version.
There are two ways of doing it:
- Use
itoa()
- add 0x30 (== '0') to each digit
Of course the 2nd method works only for single digits, so you'd rather use itoa()
in a general case.
a[0] = (char)x;
a[1] = (char)y;
should be
a[0] = x + '0';
a[1] = y + '0';
(keep the cast if you want to disable warnings)/
精彩评论