Add leading zero's to string, without (s)printf

后端 未结 7 1788
孤独总比滥情好
孤独总比滥情好 2020-12-08 19:49

I want to add a variable of leading zero\'s to a string. I couldn\'t find anything on Google, without someone mentioning (s)printf, but I want to do this without (s)printf.<

相关标签:
7条回答
  • 2020-12-08 20:22

    You could use std::string::insert, std::stringstream with stream manipulators, or Boost.Format :

    #include <string>
    #include <iostream>
    #include <iomanip>
    #include <boost/format.hpp>
    #include <sstream>
    
    int main() {
      std::string s("12");
      s.insert(0, 3, '0');
      std::cout << s << "\n";
    
      std::ostringstream ss;
      ss << std::setw(5) << std::setfill('0') << 12 << "\n";
      std::string s2(ss.str());
      std::cout << s2;
    
      boost::format fmt("%05d\n");
      fmt % 12;
      std::string s3 = fmt.str();
      std::cout << s3;
    }
    
    0 讨论(0)
提交回复
热议问题