c++ - 如何更改默认语言环境的千位分隔符?

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

我可以

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 facet 来读取千位分隔符...但是我该如何更改它?)

最佳答案

只需创建并注入(inject)您自己的 numpunct 方面:

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";
}

关于c++ - 如何更改默认语言环境的千位分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13422892/

相关文章:

c++ - 检测特定虚函数的 vtable 偏移量(使用 Visual C++)

c++ - 为什么 C++11 的 move 构造函数/赋值运算符不按预期运行

c++ - 迭代生成随机数序列

c++ - 当 const 引用参数绑定(bind)到右值时,它是否保留其 "status"?

c++ - 如何在没有 gdbserver 的情况下使用 Eclipse CDT 进行远程调试?

在调用堆栈为空的 Visual Studio 中调试小型转储

c - UTF-8 的语言环境是什么?

c++ - 在 C++ 中反转 wstring

java - 如何在应用程序中使用不同语言进行 TTS 语音朗读?

C++在线性搜索中查找最后一次出现的int