【问题标题】:How do I change the thousands separator of my default locale?如何更改默认语言环境的千位分隔符?
【发布时间】:2023-04-09 05:03:01
【问题描述】:

我可以的

locale loc(""); // use default locale
cout.imbue( loc );
cout << << "i: " << int(123456) << " f: " << float(3.14) << "\n";

它会输出:

i: 123.456 f: 3,14

在我的系统上。 (德国窗口)

我想避免使用整数的千位分隔符——我该怎么做?

(我只想要用户默认设置,但没有任何千位分隔符。)

(我的所有found 是如何读取使用use_facetnumpunct 方面的千位分隔符......但我该如何更改它?)

【问题讨论】:

  • 您愿意解决问题,还是我们必须修改千位分隔符?我感觉printf 会以您想要的格式打印,并且在打印之前将其转换为字符串很可能会达到预期的效果。
  • @evanmcdonnal - 我真的想要一个没有解决方法的解决方案,尤其是没有 printf 的解决方案。我只想要用户的默认设置,但没有任何千位分隔符。
  • 哭泣,因为 IO 流和语言环境很烂。
  • @DeadMG - 确实如此。尤其是它们的(不)记录方式很糟糕。

标签: c++ visual-c++ locale iostream


【解决方案1】:

只需创建和灌输您自己的numpunct facet:

struct no_separator : std::numpunct<char> {
protected:
    virtual string_type do_grouping() const 
        { return "\000"; } // groups of 0 (disable)
};

int main() {
    locale loc("");
    // imbue loc and add your own facet:
    cout.imbue( locale(loc, new no_separator()) );
    cout << "i: " << int(123456) << " f: " << float(3.14) << "\n";
}

如果您必须创建一个特定的输出供另一个应用程序读取,您可能还需要覆盖 virtual char_type numpunct::do_decimal_point() const;

如果您想使用特定的语言环境作为基础,您可以从_byname 方面派生:

template <class charT>
struct no_separator : public std::numpunct_byname<charT> {
    explicit no_separator(const char* name, size_t refs=0)
        : std::numpunct_byname<charT>(name,refs) {}
protected:
    virtual string_type do_grouping() const
        { return "\000"; } // groups of 0 (disable)
};

int main() {
    cout.imbue( locale(std::locale(""),  // use default locale
        // create no_separator facet based on german locale
        new no_separator<char>("German_germany")) );
    cout << "i: " << int(123456) << " f: " << float(3.14) << "\n";
}

【讨论】:

  • 我对@9​​87654326@ 感到困惑 - 这是一个 NUL 后跟两个零,不是吗?
  • @MartinBa 这是一个空值,以这样一种方式表示,如果下一个字符是八进制数字,它不会更改为另一个字符(你不能用十六进制表示法做到这一点,它没有有限制的字符数)。
  • @MartinBa \nnnescape 序列实际上是八进制的。该方面允许您创建一个自定义序列,如 "\001\003\002",这将导致 12.345.6 分组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2023-03-15
  • 2013-12-27
相关资源
最近更新 更多