c++ - cout.rdbuf(fout.rdbuf()) 之后哪个语言环境将应用于 cout?

标签 c++ unicode internationalization locale iostream

#include <locale>
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    ofstream fout("test.txt");

    fout.imbue(locale("chs"));
    cout.imbue(locale("C"));

    cout.rdbuf(fout.rdbuf());
    cout << "中文"; // Which locale will apply to here? "C" or "chs"?
}

问题已在代码中注释。

最佳答案

来自http://www.cplusplus.com/reference/ios/ios/imbue/

std::ios::imbue <ios>

locale imbue ( const locale& loc );

Imbue locale

Associates loc to both the stream and its associated stream buffer (if any) as the new locale object to be used with locale-sensitive operations.

All callback functions registered with register_callback with imbue_event as its first parameter are called.

In fact, this member function calls its inherited homonym ios_base::imbue(loc), and if the stream is associated with a stream buffer, also calls rdbuf()->pubimbue(loc).

另请参阅http://stdcxx.apache.org/doc/stdlibug/27-4.html

27.4.4 Collaboration of Locales and Iostreams

The base class ios_base contains a locale object. The formatting and parsing functions defined by the derived stream classes use the numeric facets of that locale.

The class template basic_ios holds a pointer to the stream buffer. This stream buffer has a locale object, too, usually a copy of the same locale object used by the functions of the stream classes. The stream buffer's input and output functions use the code conversion facet of the attached locale.

在您的情况下,它将使用“C”数字区域设置和“chs”字符区域设置。

关于c++ - cout.rdbuf(fout.rdbuf()) 之后哪个语言环境将应用于 cout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14719330/

相关文章:

bash - macOS上的curl与unicode字符的问题

python - 解码包含双黑斜杠的 Python Unicode 字符串

angular - 如何从 Angular 6 自动生成的 XLIFF 文件中删除位置、源文件和行号?

Spring 对自定义验证消息使用了错误的编码

angular - 以 Angular 更改默认语言环境

使用 std::vector 的 c++ 矩阵初始化

c++ - 在指针场景中使用 std::shared_ptr

python - 如何在 Python 中修复此 unicode/cPickle 错误?

c++ - 如何在 MFC/MDI 项目中指定 CDialogBar 的大小?

c++ - 如何将文件中的团队信息解析并存储到类中?