C ++: print Unicode file contents to console in Windows

I read a bunch of articles and forums discussing this problem, all solutions seem too complicated for such a simple task.

Here is a sample code directly from cplusplus.com:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

It works fine as long as example.txt only has ASCII characters. Things become messy if I try to add, say, something in Russian.

On GNU / Linux, it is as simple as saving a file as UTF-8.

On Windows, this does not work. Converting a file to UCS-2 Little Endian (which Windows apparently uses by default) and wchar_t does not do all the changes in its colleagues either.

Is there any “right” way to do this without doing all kinds of magic coding transforms?

+5
6

Windows unicode, . . UTF-16 Visual ++, :

   _setmode(_fileno(stdout), _O_U16TEXT);   

wcout cout.

UTF8, UTF-8 MultiBytetoWideChar

+6

Windows cout , GetConsoleOutputCP, . WriteConsoleW, wchar_t*.

+2

UTF-8 UTF-16 mode _ wfopen_s fgetws. , ++ . :

#include <fcntl.h>
#include <io.h>
#include <stdio.h>

int main(void) {
    _setmode(_fileno(stdout), _O_U16TEXT);
    wprintf(L"\x043a\x043e\x0448\x043a\x0430 \x65e5\x672c\x56fd\n");
    return 0;
}

GetConsoleOutputCP, 8- API.

+1

Windows UCS-2, UTF-8 .

, UTF-8, API. , . [cmd.exe] UTF-8 , .

Unicode.

hth.,

0
#include <stdio.h>

int main (int argc, char *argv[])
{
    // do chcp 65001 in the console before running this
    printf ("γασσο γεο!\n");
}

, chcp 65001 .

:

  • 64- Windows 7 V++ Express 2010
  • , UTF-8 . , V++ IDE, V++ .
  • TrueType -

, ...

BMP, .

0

, UTF8. UTF8 - , Unicode. Unicode .

Visual Studio 2008. , Visual Studio.

   #include <iostream>
   #include <fnctl.h>
   #include <io.h>
   #include <tchar.h>

   <code ommitted>


   _setmode(_fileno(stdout), _O_U16TEXT); 

   std::wcout << _T("This is some text to print\n");

I used macros to switch between std :: wcout and std :: cout, and also to remove the _setmode call to build ASCII, which allows you to compile for either ASCII or UNICODE. It works. I have not tested using std :: endl yet, but I could work with wcout and Unicode (not sure), i.e.

   std::wcout << _T("This is some text to print") << std::endl;
-1
source

All Articles