简体   繁体   中英

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;

but when i am displaying this temp, it's displaying ?8. should display 98.

can anyone please help???

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;
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.

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, eg), 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:

  1. Use itoa()
  2. 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)/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM