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

后端 未结 7 1826
孤独总比滥情好
孤独总比滥情好 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:13

    I can give this one-line solution if you want a field of n_zero zeros:

      std::string new_string = std::string(n_zero - old_string.length(), '0') + old_string;
    

    For example: old_string = "45"; n_zero = 4; new_string = "0045";

提交回复
热议问题