tags:

views:

103

answers:

6
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???

+4  A: 

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;
Goz
This is the correct answer.
DeadMG
+1  A: 

Or, more generic

template <class T> string toString (const T& obj)
    {
    stringstream ss;
    ss << obj;
    return ss.str();
    }
nico
Congratulations, you have just reinvented `boost::lexical_cast` ;)
FredOverflow
@FredOverlow: hmmm... my C++ is a bit rusty... never really used boost before, but I'm glad I reinvented the wheel :P
nico
+3  A: 
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.

Poni
what should be done???
SPB
printf? in C++? insane?
DeadMG
i am using printf..but its not displaying 98...whereas individually i tried a[0] and a[1]....its working
SPB
Insane, I admit (: @SPB: The difference is that I gave x and y the ASCII value of 8 and 9, instead of the numerical values (8 and 9).
Poni
"int x='9'; int y='8';" <<<< only this differs from your code.
Poni
i agree but if u are getting 9 and 8 from some function then??i am storing some return value in these integers.
SPB
add `'0'` to the function return, as in `a[0]=GetFirstDigit()+'0'`.
Blindy
i tried its adding some extra value and then displaying the corresponding char
SPB
http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
Poni
A: 

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.

slaimi
+1  A: 

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.

A: 
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)/

Alexandre C.