所以通常情况下,如果我想在一些数字 foo
中插入适当的区域设置分隔符,我会做这样的事情:
ostringstream out;
out.imbue(locale("en-US"));
out << foo;
然后我可以使用 out.str()
作为分隔字符串:http://coliru.stacked-crooked.com/a/054e927de25b5ad0
不幸的是,我被要求不要在我当前的项目中使用 stringstreams
。我还有其他方法可以做到这一点吗?理想情况下是依赖于语言环境的方式?
最佳答案
所以这个答案是 Jerry Coffin 对这个问题的回答的 C++ 提炼:Cross Platform Support for sprintf's Format '-Flag
template <typename T>
enable_if_t<is_integral_v<remove_reference_t<T>>, string> poscommafmt(const T N, const numpunct<char>& fmt_info) {
const auto group = fmt_info.grouping();
auto posn = cbegin(group);
auto divisor = static_cast<T>(pow(10.0F, static_cast<int>(*posn)));
auto quotient = div(N, divisor);
auto result = to_string(quotient.rem);
while(quotient.quot > 0) {
if(next(posn) != cend(group)) {
divisor = static_cast<T>(pow(10.0F, static_cast<int>(*++posn)));
}
quotient = div(quotient.quot, divisor);
result = to_string(quotient.rem) + 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")))
关于c++ - 没有 stringstream 的逗号分隔数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44502040/