首页 > 解决方案 > std::wofstream << WCHAR 和 << CHAR 可以同时吗?

问题描述

我们如何同时将 WCHAR 和 CHAR 写入 wofstream?像这样:

wofstream << L"汉字" << "汉字"

这是用于测试的东西。我只能“wofstream<<WCHAR”或“wofstream<<CHAR”,但不能同时“wofstream<<WCHAR<<CHAR”。

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

int main() {
    std::wofstream wof2;
    wof2.open(L"2.txt", std::wofstream::app);
    wof2 << "\nCHAR 汉&quot;;
    wof2.flush();
    wof2 << L"\nWCHAR 汉&quot;;
    wof2.close();
    
    const char * tmp = setlocale(LC_ALL, "");
    std::cout << tmp << std::endl;
    std::locale::global(std::locale(""));
    wof2.open(L"2.txt", std::wofstream::app);
    wof2.imbue(std::locale());

    wof2 << L"\nWCHAR after imbue";
    wof2.flush();
    wof2 << L"\nWCHAR 汉&quot;;
    wof2.flush();
    wof2 << "\nCHAR汉&quot;;
    wof2.flush();

    return 0;
}

我们可以在控制台看到

Chinese (Simplified)_China.936

但是在 2.txt 中,我看到了

CHAR 汉
WCHAR 
WCHAR after imbue
WCHAR 汉
CHAR

标签: c++localechinese-localewcharwofstream

解决方案


推荐阅读