c++ - 没有 stringstream 的逗号分隔数

标签 c++ locale number-formatting stringstream separator

所以通常情况下,如果我想在一些数字 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")))

Live Example

关于c++ - 没有 stringstream 的逗号分隔数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44502040/

相关文章:

facebook - 从 Facebook Graph API 获取语言代码/区域

python - 如何使用带逗号小数点分隔符的 pandas.to_clipboard

c++ - 创建具有正确边的无向图

c++ - 你能解释一下 extern 的意思和其他一些东西吗?

c++ - 如何更新旧的 C 代码?

c++ - 为什么我不能使用 fopen?

java - 用于在 Linux 上访问带有瑞典字符的文件的 Java 代码错误

sorting - 按字母顺序对包含 UTF-8 编码值的表进行排序

c# - 如何用上标的幂格式化科学记数法中的数字

python - 使用不同区域设置设置百分比格式(逗号为小数)