Convert a number to a string with specified length in C++

后端 未结 8 1342
情深已故
情深已故 2020-12-04 23:36

I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then tho

8条回答
  •  萌比男神i
    2020-12-05 00:01

    or using the stringstreams:

    #include 
    #include 
    
    std::stringstream ss;
    ss << std::setw(10) << std::setfill('0') << i;
    std::string s = ss.str();
    

    I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.

提交回复
热议问题