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

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

    This works well for me. You don't need to switch setfill back to ' ', as this a temporary stream.

    std::string to_zero_lead(const int value, const unsigned precision)
    {
         std::ostringstream oss;
         oss << std::setw(precision) << std::setfill('0') << value;
         return oss.str();
    }
    

提交回复
热议问题