Padding stl strings in C++

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>


void padTo(std::string &str, const size_t num, const char paddingChar = ' ')
{
    if(num > str.size())
        str.insert(0, num - str.size(), paddingChar);
}

int main(int argc, char **argv)
{
    std::string str = "abcd";
    padTo(str, 10);
    return 0;
}

You can use it like this:

std::string s = "123";
s.insert(s.begin(), paddedLength - s.size(), ' ');

The easiest way I can think of would be with a stringstream:

string foo = "foo";
stringstream ss;
ss << setw(10) << foo;
foo = ss.str();

foo should now be padded.


you can create a string containing N spaces by calling

string(N, ' ');

So you could do like this:

string to_be_padded = ...;
if (to_be_padded.size() < 10) {
  string padded(10 - to_be_padded.size(), ' ');
  padded += to_be_padded;
  return padded;
} else { return to_be_padded; }