Padding stl strings in C++

Alex B picture Alex B · Mar 20, 2009 · Viewed 76.5k times · Source

I'm using std::string and need to left pad them to a given width. What is the recommended way to do this in C++?

Sample input:

123

pad to 10 characters.

Sample output:

       123

(7 spaces in front of 123)

Answer

bayda picture bayda · Mar 20, 2009

std::setw (setwidth) manipulator

std::cout << std::setw (10) << 77 << std::endl;

or

std::cout << std::setw (10) << "hi!" << std::endl;

outputs padded 77 and "hi!".

if you need result as string use instance of std::stringstream instead std::cout object.

ps: responsible header file <iomanip>