Padding stl strings in C++

后端 未结 12 1871
一向
一向 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:10

    Minimal working code:

    #include 
    #include 
    
    int main()
    {
        for(int i = 0; i < 300; i += 11)
        {
            std::cout << std::setfill ( ' ' ) << std::setw (2) << (i % 100) << std::endl;
        }
        return 0;
    }
    
    /*
    Note:
    - for std::setfill ( ' ' ):
      - item in '' is what will be used for filling
    - std::cout may be replaced with a std::stringstream if you need it
    - modulus is used to cut the integer to an appropriate length, for strings use substring
    - std::setw is used to define the length of the needed string
    */
    

提交回复
热议问题