gpt4 book ai didi

c++ - 如何将 std::to_string 函数的预填充归零?

转载 作者:搜寻专家 更新时间:2023-10-31 01:27:22 24 4
gpt4 key购买 nike

在使用 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
}
}

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

添加:来自 Add leading zero's to string, without (s)printf ,我发现

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

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

最佳答案

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

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

关于c++ - 如何将 std::to_string 函数的预填充归零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com