Padding stl strings in C++

后端 未结 12 1802
一向
一向 2020-12-05 22:15

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
         


        
12条回答
  •  情深已故
    2020-12-05 23:03

    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

提交回复
热议问题