不含字符串流的逗号分隔数字 [英] Comma Separate Number Without stringstream

查看:65
本文介绍了不含字符串流的逗号分隔数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,通常,如果我想在一些数字foo中插入适合区域设置的分隔符,我会执行以下操作:

So typically if I wanted to insert locale appropriate separators in some number, foo, I'd do something like this:

ostringstream out;

out.imbue(locale("en-US"));
out << foo;

然后,我可以使用out.str()作为分隔字符串: http://coliru. stacked-crooked.com/a/054e927de25b5ad0

Then I could just use out.str() as the separated string: http://coliru.stacked-crooked.com/a/054e927de25b5ad0

不幸的是,我被要求不要在当前项目中使用stringstreams.我还有其他方法可以做到这一点吗?理想情况下是依赖于语言环境的方式?

Unfortunately I've been asked not to use stringstreams in my current project. Is there any other way I can accomplish this? Ideally a locale dependent way?

推荐答案

因此,此答案是Jerry Coffin对以下问题的答案的C ++精炼:

So this answer is the C++ distillation of Jerry Coffin's answer to this question: 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的补语否定问题.

Naturally this suffers from the identical 2's compliment negation issue.

这当然得益于C ++的string内存管理,而且还得益于传递特定的numpunct<char>的能力,而该特定numpunct<char>不必是当前语言环境.例如,是否可以调用cout.getloc() == locale("en-US"):commafmt(foo, use_facet<numpunct<char>>(locale("en-US")))

This certainly benefits from C++'s string memory management, but also from the ability to pass in a specific numpunct<char> which need not be the current locale. For example whether or not cout.getloc() == locale("en-US") you can call: commafmt(foo, use_facet<numpunct<char>>(locale("en-US")))

在线示例

这篇关于不含字符串流的逗号分隔数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆