C++ can setw and setfill pad the end of a string?

Dan picture Dan · Aug 21, 2012 · Viewed 35.7k times · Source

Is there a way to make setw and setfill pad the end of a string instead of the front?

I have a situation where I'm printing something like this.

 CONSTANT TEXT variablesizeName1 .....:number1 

 CONSTANT TEXT varsizeName2 ..........:number2

I want to add a variable amount of '.' to the end of

"CONSTANT TEXT variablesizeName#" so I can make ":number#" line up on the screen.

Note: I have an array of "variablesizeName#" so I know the widest case.

Or

Should I do it manually by setting setw like this

for( int x= 0; x < ARRAYSIZE; x++)
{
string temp = string("CONSTANT TEXT ")+variabletext[x];
cout <<  temp;
cout << setw(MAXWIDTH - temp.length) << setfill('.') <<":";
cout << Number<<"\n";
}

I guess this would do the job but it feels kind of clunky.

Ideas?

Answer

jrok picture jrok · Aug 21, 2012

You can use manipulators std::left, std::right, and std::internal to choose where the fill characters go.

For your specific case, something like this could do:

#include <iostream>
#include <iomanip>
#include <string>

const char* C_TEXT = "Constant text ";
const size_t MAXWIDTH = 10;

void print(const std::string& var_text, int num)
{
    std::cout << C_TEXT
              // align output to left, fill goes to right
              << std::left << std::setw(MAXWIDTH) << std::setfill('.')
              << var_text << ": " << num << '\n';
}

int main()
{
    print("1234567890", 42);
    print("12345", 101);
}

Output:

Constant text 1234567890: 42
Constant text 12345.....: 101

EDIT: As mentioned in the link, std::internal works only with integer, floating point and monetary output. For example with negative integers, it'll insert fill characters between negative sign and left-most digit.

This:

int32_t i = -1;
std::cout << std::internal
          << std::setfill('0')
          << std::setw(11)  // max 10 digits + negative sign
          << i << '\n';
i = -123;
std::cout << std::internal
          << std::setfill('0')
          << std::setw(11)
          << i;

will output

-0000000001
-0000000123