buffer problem

hi

i want make hexdecimal number in a buffer then put them in a char pointer :
like that:

stringstream ss (stringstream::in | stringstream::out);
int a = 0x25;
int b = 0x0c;
char *y = new char;
ss << std::hex << a;
ss << std::hex << b;

ss >> y;

std::cout << y << std::endl;

What i got : 25c
But what i want to get is 250c , i don't know why "0" not added !!

Did any one have idea to have the right result ??
Thanks
You can use setw() and setfill() (with 2/0 instead of that in the example):

http://www.cplusplus.com/reference/iostream/manipulators/setfill/
Why should it write the zero? Do we write 0015? b is just a number, and you're telling your computer to output that number for you.
Use stream manipulators to pad with zeros:
 
ss<<std::setw(2)<<std::setfill('0');


Setw forces it to print that many characters, and setfill tells it to use that character for padding.
This is really bad:
1
2
3
4
stringstream ss;
char *y = new char;
//...
ss >> y;
Instead, do this:
1
2
3
ostringstream ss;
//...
std::string str = ss.str();
the problem that here i know where i have '0' , but in my work , i have variable i don't know when i will got '0' and when not .
i can have 0x00 or 0x05 or 0x20 .....

So how can i solve this problem ?
You're not seeing the leading 0 when you write 0xc because the field width hasn't been set.

See coder777's post above to set the field width and fill character.
Last edited on
Topic archived. No new replies allowed.