所以这个答案是杰里棺材的答案的C++蒸馏到这样一个问题:Cross Platform Support for sprintf's Format '-Flag
template <typename T>
enable_if_t<is_integral_v<remove_reference_t<T>>, string> poscommafmt(T N, const numpunct<char>& fmt_info) {
string result = to_string(N % 10);
const auto group = fmt_info.grouping();
auto places = 0U;
for (auto posn = '\1'; 0 != (N /= 10); ++posn, result = to_string(N % 10) + result) {
if (group[places] == posn) {
if (places + 1U < size(group)) {
++places;
}
posn = '\0';
result = fmt_info.thousands_sep() + result;
}
}
return result;
}
template <typename T>
enable_if_t<is_integral_v<remove_reference_t<T>>, string> commafmt(const T N, const numpunct<char>& fmt_info) {
return N < 0 ? '-' + poscommafmt(-N, fmt_info) : poscommafmt(N, fmt_info);
}
当然,这从相同的2的补否定问题受到影响。
这肯定会受益于C++的string
内存管理,还有能力传入一个特定的numpunct<char>
,它不一定是当前的语言环境。例如是否cout.getloc() == locale("en-US")
您可以拨打:commafmt(foo, use_facet<numpunct<char>>(locale("en-US")))
Live Example
所以,你想一个数字转换为千个分隔字符串或字符串千分隔字符串或者你只是需要输出这种方式? – NathanOliver
@NathanOliver是的,显然我可以手动插入它们。但是这不会是适合当地语言的:( –
)难道你不能仅仅使用[this](https://stackoverflow.com/questions/17530408/print-integer-with-thousands-and-millions-separator)吗?除非你真的需要一个字符串 – NathanOliver