没有字符串流的逗号分隔号

时间:2017-06-12 14:32:52

标签: 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。有没有其他方法可以实现这一目标?理想情况下,依赖于语言环境的方式?

2 个答案:

答案 0 :(得分:1)

所以这个答案是Jerry Coffin对这个问题的回答: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);
}

当然,这会遭受同样的恭维否定问题。

这肯定会受益于C ++的string内存管理,但也能传递一个不需要当前语言环境的特定numpunct<char>。例如,您是否可以致电cout.getloc() == locale("en-US")commafmt(foo, use_facet<numpunct<char>>(locale("en-US")))

Live Example

答案 1 :(得分:0)

设置管道。使用链接到代码construct an ofstream and ifstream from a file descriptor,然后输出到另一个并从另一个读取。

这是一个奇怪且扭曲的解决方案。但是,你必须使用区域设置,必须存储东西,不能使用stringstream的想法同样奇怪。所以,他们给你奇怪的要求,他们得到了奇怪的代码。