'How to set maximum field width for a std::string with iomanip?

std::setw() sets the minimum field width for all output, and std::setprecision() is capable of affecting floats, but is there a way to set the maximum field width for a std::string, to achieve the same result as the following printf() format specifier: %10.10s

I am aware that boost::format may be capable of doing this, but I am looking for a solution that is strictly C++ standards only, no third party software.



Solution 1:[1]

Maybe this?

std::string string_w(char *c_str, int width)
{
    int pad = width - strlen(c_str);
    return (std::string(c_str) + std::string(pad > 0 ? pad : 0, ' ')).substr(0,width);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1