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

时间:2012-11-16 19:11:46

标签: 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

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

我想避免获得整数千个分隔符 - 我该怎么做?

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

(所有I found是如何使用use_facet方面使用numpunct 读取数千个分隔符...但我该如何更改呢?)

1 个答案:

答案 0 :(得分:9)

只需创建并灌输您自己的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";
}
相关问题