【问题标题】:Comma Separate Number Without stringstream没有字符串流的逗号分隔数字
【发布时间】:2017-11-14 02:00:12
【问题描述】:

因此,通常如果我想在某个数字 foo 中插入适合区域设置的分隔符,我会这样做:

ostringstream out;

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

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

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

【问题讨论】:

  • 所以你想将一个数字转换为千位分隔的字符串或将一个字符串转换为千位分隔的字符串,还是只需要这样输出?
  • @NathanOliver 是的,显然我可以手动插入它们。但这不适合语言环境:(
  • 看起来您可以使用this,但使用sprintf 而不是printf
  • 看起来那只是一个 C 特性。无赖。
  • 不使用stringstream 是一个奇怪的要求。特别是如果您还必须处理语言环境。

标签: c++ locale number-formatting stringstream separator


【解决方案1】:

所以这个答案是 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&lt;char&gt; 的能力,该 numpunct&lt;char&gt; 不必是当前语言环境。比如cout.getloc() == locale("en-US")是否可以拨打:commafmt(foo, use_facet&lt;numpunct&lt;char&gt;&gt;(locale("en-US")))

Live Example

【讨论】:

    【解决方案2】:

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

    这是一个奇怪而扭曲的解决方案。但是,您必须使用语言环境,必须存储东西并且不能使用stringstream 的想法同样奇怪。所以,他们给你奇怪的要求,他们得到奇怪的代码。

    【讨论】:

    • 哈哈,我可以保证这不会通过审查:)
    • @JonathanMee - 然后您可以向他们询问满足要求的更好方法。 :-) 有时,这是迫使愚蠢的决定得到他们应得的审查的最佳方式。我已经告诉测试部门要放入哪些测试用例来触发我知道存在但开发人员不承认的错误。有时,您必须破解的是组织而不是代码。
    • 这可能是一个合理的建议。当编写一个单独的程序来解决这个问题时,你知道事情已经变得很糟糕了。
    • @JonathanMee - 请问避免stringstream的理由是什么?
    • @JonathanMee - 我认为你没有回答 Omnifarious 最后一个问题。您能否再试一次:编码标准是否说明了为什么“不使用流”?有人记得不使用流的理由吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多