sprintf question

chrisben (75)
if I do

char b[5];
sprintf(b,%-5s","A");
cout << b << "X" << endl;

I will get

A X

With 4 spaces place holder for the output. How can I create a string as

A++++X

Basically, want to output a string padded right with "+", with total length 5.

Thanks
PanGalactic (1571)
http://www.cplusplus.com/reference/iostream/manipulators/

Play around with setfill, setw and left or right as appropriate.
kbw (4342)
The buffer passed to sprintf isn't big enough and will be overrun.
chrisben (75)
thanks. setfill is nice. but how can I change the value of b itself? As I need to pass this format to a string variable eventually (as assigning string s = "A++++";), and setfill seems only set the cout format.
PanGalactic (1571)
stringstream is what you want.

1
2
3
4
5
#include <sstream>

std::ostringstream os;
os << "A" << ... << "X" << endl;
std::string s = os.str();

Last edited on
Topic archived. No new replies allowed.