如何对 std::to_string 函数进行零预填充?

Cha*_*Kim 6 c++ printing string

在使用 std::to_string() 的 C++ 中,我应该如何预填充从整数转换的字符串?我尝试使用 #include 和 std::setfill('0') 但它没有用。这是简单的测试代码。

#include <iostream>
#include <string>
//#include <iomanip> // setw, setfill below doesn't work

int main()
{
int i;
for (i=0;i<20;i++){
    std::cout << "without zero fill : " << std::to_string(i) << ", with zero fill : " << std::to_string(i) << std::endl;
    //std::cout << std::setw(3) << std::setfill('0') << "without zero fill : " << std::to_string(i) << ", with zero fill : " << std::to_string(i) << std::endl;  // doesn't work
}
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是,将一些数字转换为字符串,但其中一些带有零填充,其他则没有。(我实际上是用它来制作文件名。)我该怎么做?
(我不知道为什么这不像在 C 中使用 %0d 或 %04d 格式说明符那么简单。)

ADD :从将前导零添加到字符串,没有 (s)printf,我发现

int number = 42;
int leading = 3; //6 at max
std::to_string(number*0.000001).substr(8-leading); //="042"
Run Code Online (Sandbox Code Playgroud)

这对我有用,但我更喜欢更自然的解决方案,而不是像这种技巧一样的方法。

Evg*_*Evg 6

ostringstream似乎是矫枉过正。您可以简单地插入所需的零数:

template<typename T/*, typename = std::enable_if_t<std::is_integral_v<T>>*/>
std::string to_string_with_zero_padding(const T& value, std::size_t total_length)
{
    auto str = std::to_string(value);
    if (str.length() < total_length)
        str.insert(str.front() == '-' ? 1 : 0, total_length - str.length(), '0');
    return str;
}
Run Code Online (Sandbox Code Playgroud)

如果value为负数和/或 if Tischar或相关类型,此函数也能正常工作。


R S*_*ahu 3

std::to_string()您可以使用std::ostringstream. IO 操纵器将与std::ostringstream.

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
   for ( int i = 1; i <= 10; ++i )
   {
      std::ostringstream str;
      str << std::setw(3) << std::setfill('0') << i;
      std::cout << str.str() << std::endl;
   }
}
Run Code Online (Sandbox Code Playgroud)

输出:

001
002
003
004
005
006
007
008
009
010
Run Code Online (Sandbox Code Playgroud)

请在https://ideone.com/ay0Xzp上查看它的工作情况。