1

How can we write WCHAR and CHAR to a wofstream at the same time?like this:

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

Here is something for testing. I can only "wofstream<<WCHAR" or only "wofstream<<CHAR", but can't "wofstream<<WCHAR<<CHAR" both at the same time.

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

int main() {
    std::wofstream wof2;
    wof2.open(L"2.txt", std::wofstream::app);
    wof2 << "\nCHAR 汉";
    wof2.flush();
    wof2 << L"\nWCHAR 汉";
    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 汉";
    wof2.flush();
    wof2 << "\nCHAR汉";
    wof2.flush();

    return 0;
}

We can see that at the console

Chinese (Simplified)_China.936

But In the 2.txt, I see that

CHAR 汉
WCHAR 
WCHAR after imbue
WCHAR 汉
CHAR
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
Li Da
  • 41
  • 4
  • _How can we write WCHAR and CHAR to a wofstream at the same time?_ I guess, the real question is: How can we write the same glyph encoded as character (code point) in two different encodings write to `std::wofstream`? If there is no "accidental" co-incidence (like e.g. `A` is `0x41` in ASCII _and_ Unicode (and all western encodings I know)) this should be impossible. Or do I basically mis-understand your question? – Scheff's Cat Aug 17 '18 at 06:10
  • What version of Visual Studio are you using? Try doing the same thing as this answer suggests: [Shift-JIS decoding fails using wifstrem in Visual C++ 2013](//stackoverflow.com/a/26626263) – wilx Sep 14 '18 at 05:08

0 Answers0