Search code examples
c++formattingiostream

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

  • There isn't a built in way to do this with C++ streams. One way to do this is to use a std::string_view to just get the slice that you want like

    #include <iostream>
    #include <string_view>
    
    std::string_view print_max(std::string_view sv, std::size_t width)
    {
        return sv.substr(0, width);
    }
    
    
    int main()
    {
        std::cout << print_max("0123456789", 3) << "\n";
        std::cout << print_max("0123456789", 5) << "\n";
        std::cout << print_max("0123456789", 8) << "\n";
        std::cout << print_max("0123456789", 20);
    }
    

    Output:

    012
    01234
    01234567
    0123456789