0

I have a simple code and argv[1] is "Привет".

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <locale.h>

int _tmain(int argc, TCHAR* argv[])
{
    TCHAR buf[100];

    _fgetts(buf, 100, stdin);

    _tprintf(TEXT("\nargv[1] %s\n"), argv[1]);
    _tprintf(TEXT("%s\n"), buf);
}

In the console, I write "Мир" and have this result:

image

If I use setlocale(LC_ALL, ""), I have this result:

image

What should I do to get the correct string in both cases?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
tproger
  • 77
  • 7
  • 1
    The simplest thing would be to simply set your application character set as unicode, and not worry about encoding at all. – Chris Becke May 12 '17 at 13:17
  • 2
    Possible duplicate of [Output unicode strings in Windows console app](http://stackoverflow.com/questions/2492077/output-unicode-strings-in-windows-console-app) – Mgetz May 12 '17 at 13:19
  • Are you using of not Unicode? What is you current encoding? Do you get that in the console? Currently, your question is unclear... – Serge Ballesta May 12 '17 at 13:45
  • 1
    Do you compile with `/D _UNICODE /D UNICODE`? – Ian Abbott May 12 '17 at 13:48
  • 2
    I don't understand why people use TCHAR in new code. TCHAR is a *compatibility hack*. The idea was that you could take your old narrow-encoding code and do a bunch of search-and-replace changes and then compile with -DUNICODE and magically get Unicode awareness. In new code, why wouldn't you just use `wchar_t` and the FooW APIs throughout? – zwol May 12 '17 at 14:39
  • 2
    @zwol probably because the majority of the Win32 API documentation is still `TCHAR` oriented. Only new APIs are Unicode-only, but older APIs that match the documentation and examples are `TCHAR` based. – Remy Lebeau May 12 '17 at 15:58
  • Yes @Ian Abbott – tproger May 13 '17 at 10:05

1 Answers1

2

Evidently your program works, except it cannot print correctly on the console window. This is because Windows console is not fully compatible with Unicode. Use _setmode for Visual Studio. This should work for Russian but there could be additional problems with some Asian languages. Use WriteConsole for other compilers.

Visual Studio Example:

#include <stdio.h>
#include <io.h> //for _setmode
#include <fcntl.h> //for _O_U16TEXT

int wmain(int argc, wchar_t* argv[])
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    wprintf(L"%s", L"Привет\n");

    return 0;
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77