Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Does anybody of the readers know a way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
273 views
Welcome To Ask or Share your Answers For Others

1 Answer

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";


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...