How can I format stream not in such an awkward way?

S

Steven Woody

Here is the code,

uint16_t n1, n2;
...
std::eek:stringstream os;
os << "(" << std::hex << std::setw(4) << std::setfill('0')
<< n1 << "," << std::setw(4) << std::setfill('0')
<< n2 << ")";

You see, I have to used setw,setfill twice for print two integer.
This is the only we I found works. Is there a simple representaion to
archive same purpose?

Thanks!

-
narke
 
M

Michael DOUBEZ

Steven Woody a écrit :
Here is the code,

uint16_t n1, n2;
...
std::eek:stringstream os;
os << "(" << std::hex << std::setw(4) << std::setfill('0')
<< n1 << "," << std::setw(4) << std::setfill('0')
<< n2 << ")";

You see, I have to used setw,setfill twice for print two integer.
This is the only we I found works. Is there a simple representaion to
archive same purpose?

You don't need the second std::setfill('0') but you need a setw() for
each output concerned.
If you do:
os<<std::setw(4) << std::setfill('0')<<",";
output is '000,'.
os.setf(ios::hex, ios::basefield)
os.fill('0');
os << "("
<< std::setw(4) << n1 << ","
<< std::setw(4) << n2
<< ")";
 
S

Steven Woody

Steven Woody a écrit :




You don't need the second std::setfill('0') but you need a setw() for
each output concerned.
If you do:
os<<std::setw(4) << std::setfill('0')<<",";
output is '000,'.
os.setf(ios::hex, ios::basefield)
os.fill('0');
os << "("
<< std::setw(4) << n1 << ","
<< std::setw(4) << n2
<< ")";

Thank you, I understand.
 
J

James Kanze

Here is the code,
uint16_t n1, n2;
...
std::eek:stringstream os;
os << "(" << std::hex << std::setw(4) << std::setfill('0')
<< n1 << "," << std::setw(4) << std::setfill('0')
<< n2 << ")";
You see, I have to used setw,setfill twice for print two
integer. This is the only we I found works. Is there a
simple representaion to archive same purpose?

os << '(' << HexFmt( 4 ) << n1 << ',' << HexFmt( 4 ) << n2 <<
')' ;

More generally, the standard manipulators (except maybe for
setw) are really only there to serve as examples. You wouldn't
normally use them in real code; you'd define application
specific manipulators, like HexFmt above. (My implementation of
HexFmt is available at my site, but more generally, you'll want
to provide your own, since only you know what logical markup is
applicable to your application.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top