将数字转换为填充字符串
Converting number to a padded string
我正在尝试将数字类型转换为带有前导'0'的固定长度字符串表示形式(用于只能处理字符串的GUI - 数字的词典排序真的很尴尬(。
我认为应该可以制作一个不错的模板供其他人使用,而不是在需要的地方创建字符串,该模板也适用于不同的算术类型。
template <typename T, typename std::enable_if<std::is_arithmetic<T>::value, T>::type* = nullptr>
std::string arithmeticToMaxLengthString(const T& value)
{
std::string number, result;
number = std::to_string( value );
result = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, number );
return result;
}
std::string lpad( char filler, std::string::size_type length, const std::string& input)
{
std::string result;
if( input.length() < length )
{
result.append( lenght - input.lenght(), filler ).append( input );
return result;
}
return input;
}
目前为止,一切都好。 它可以编译,我可以使用它。 但:
当我尝试使用它时,我得到了一个惊喜。 使用int32_t调用此函数,该
typedef int int32_t;
值为 100的结果是字符串"100",长度为 3。
我很确定代码库中不存在其他名称如此糟糕的模板(我已经搜索了所有这些模板以及所有链接库(,但我似乎无法理解我生成的代码有什么问题。 为了验证代码是否正确,我只是将其复制粘贴到调用它的位置,现在基本上看起来像这样:
myDataClass{
int32_t quantity;
std::string numberAsString;
}
void setNumberString( myDataClass data )
{
std::string result = arithmeticToMaxLengthString( data.quantity );
std::string reference = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, std::to_string(data.quantity) );
std::cout << "quantity<" << data.quantity << "> numericLimits<" << std::numeric_limits<decltype(value)>::digits10 + 1 << ">" << std::endl;
std::cout << "result template: length<" << result.lenght() << "> content<" << result << ">" << std::endl;
std::cout << "result reference: length<" << reference.lenght() << "> content<" << reference << ">" << std::endl;
}
现在据我了解,模板"arithmeticToMaxLengthString"以int32_t作为参数的类型调用,这是一个普通的整数,其中"numeric_limits::d igits10 + 1"给了我10。 但是,当现在调用此功能时,数量为 100,结果会有所不同。
quantity<100> numericLimits<10>
result template: length<3> content<100>
result reference: length<10> content<0000000100>
我是否缺少有关模板、enable_if或numeric_limits的内容? 模板在哪些方面有所不同(除了明显的enable_if(?
发生此问题是因为您正在传递对arithmeticToMaxLengthString
函数的引用。由于此处另一个答案中列出的原因,std::numeric_limits
不适用于参考文献。
因此,我建议您使用模板类型T
来获取数值限制,而不是使用decltype(value)
:
result = lpad('0', std::numeric_limits<T>::digits10 + 1, number);
它不仅解决了问题,而且看起来也更加优雅。
这不是您问题的答案,而是如何使用STL
实现相同功能的建议。
#include <iomanip>
#include <sstream>
template <typename T, unsigned N = 5>
std::string to_string_with_leading_0(T element) {
std::stringstream ss;
ss << std::setw(N) << std::setfill('0') << element;
return ss.str();
}
- 将数字转换为填充字符串
- Cryptopp:获取密码输入的填充字符串
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- 使用 C++-17,如何从字符串向量填充元组
- 从函数填充的字符串的推导向量到 int 的字符串
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- strcpy_s将超过字符串长度的字符串复制到目标缓冲区(用 0xFE 填充)
- 如何调用 GetAltMonthNames 来填充外部区域设置月份字符串的安全数组
- JNI - 如何填充从 C++ 传递到 Java 的字符串
- 在字符串上迭代并填充C 中的数组
- 填充字符串的向量
- 用输入中给出的单词填充字符串
- 如何填充字符串的可变长度数组
- C++可以设置和填充字符串的末尾
- 用 '0' C++ 填充字符串流变量的右侧
- C++ 从空格分隔的文本文件中填充字符串向量
- 使用制表符分隔的文本填充字符串向量
- c++无法重新填充字符串流
- 异常构造函数来填充字符串流
- 如何填充字符串和双精度向量对的映射