Reputation: 31
We can print any English character with log by putting "%c". Take an another case. Keyboard layout has been changed. Now my input is some Korean/chinese language. We can not simply put "%c" in log to print those characters.
How can we achieve this ?
Upvotes: 3
Views: 2763
Reputation: 28997
How are you writing to the log? If it is printf
, I suggest switching to wprintf
, and make sure your keyboard input is being read into a wchar_t. Then you can use %lc
to print out your character.
The only slight catch, is that some Chinese characters don't even fit in a single wchar_t
(the ones at Unicode characters U+10000 and above). For those, you will have to read into a wchar_t
array (or a std::wstring
) and print with %ls
.
Note: The standard doesn't actually specify how big a wchar_t
is, and on Unix platforms, it is common for wchar_t
to be 32-bits, so it can hold any single Unicode code-point as a single UTC-4 value. Windows-NT was developed before it became apparent that 65536 characters wasn't enough, so the API took UTC-2 characters. When Unicode was expanded to a million characters, it would have been too disruptive to change the size of the characters accepted by the API, so they were converted to accept UTF-16. For interfacing with those APIs, wchar_t
on Windows platforms is usually a UTF-16 value.
Of course, even if wchar_t
is big enough for a code point, that doesn't help when a "character" takes more than one code point. For example U+005A LATIN CAPITAL LETTER Z & U+0303 COMBINING TILDE == Z̃ (I don't know if there's a language which uses that as a character, but there doesn't appear to be a combined form for it.)
Upvotes: 2
Reputation: 6407
As I understand, your issue relates to usage standard input/output C/C++ libraries, so the main problem is in I/O system - functions from stdio.h and streams from iostream provide input dependent from localization.
If you want remember (write to log) pressed key, without taking into account selected language, My suggestion is to use some kind of Windows API. First, read about Keyboard Input in MSDN and see Virtual Key Codes. Then, refer to examples with processing WM_KEYDOWN message, e.g. at C++ references forum.
EDIT:
But if the issue is only in writing Korean to file, solution can be in localization and data format - consider the following example:
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
int main(void)
{
// localization (perhaps needed for some computers)
setlocale(LC_CTYPE, "Korean");
// open log file for writing
FILE* outfile;
outfile = _wfopen( L"log.txt",L"wt+,ccs=UTF-16LE");
// test data
wchar_t wch = L'술';
// write one character to log file
fwrite(&wch, sizeof(wchar_t), 1, outfile);
// close file
fclose(outfile);
return 0;
}
Upvotes: 1