0
int a = getch(); int b = getch();
printf("%c%c", a, b);

This code works fine in Windows 7 or earlier, but in Windows 10 I get letters that I didn't input because b always returns 151. Is there a way to fix this? The console code pages are the same;

  • What keys did you press, and what are the "weird values"? – Weather Vane May 31 '22 at 14:22
  • I typed a single Korean letter, and "weird values" -> different letter – user16671539 May 31 '22 at 14:23
  • Be clear: is it `getch` or is it `kbhit` returning the weird values? `kbhit` does not return the key pressed, but a [non-zero value](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-170). You'll get better feedback with `printf("%X\n", a);` – Weather Vane May 31 '22 at 14:25
  • What I mean "tried hbhit" is `char a = getch(); if(kbhit()) { char b = getch(); printf("%c%c", a, b); }` – user16671539 May 31 '22 at 14:27
  • 1
    Everything in the CJK planes of unicode requires a surrogate pair for UTF-16, and at least 3 code units for UTF-8. Reading and outputting in single code units is going to be rather difficult. You'll probably have to reconfigure your console to be using code page 1200 (65001 (UTF-8) has some problems with input still) and use win32 functions for reading the input. – vandench May 31 '22 at 14:30
  • Don't use `char` because `getch()` returns `int`, and also printing "weird characters" doesn't tell you much. Please post *specific integer values* in the question. Even without Korean, `getch` must be called twice when a function key or cursor key is pressed - depending on what the first value is. So write a simple loop that prints **integer values** so you can analyse what is going on. In my 2-value example, the first of the two is `0` or `224`. – Weather Vane May 31 '22 at 14:31
  • I just checked second getch() always returns 151 in Windows 10 – user16671539 May 31 '22 at 14:40
  • Note C17 6.7.9/23: *"The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified."* So `int a = getch(), b = getch();` should be changed to `int a = getch(); int b = getch();` to guarantee that the results of the two calls to `getch()` are assigned to the correct variables. – Ian Abbott May 31 '22 at 15:03
  • I tried that too. – user16671539 May 31 '22 at 15:10

0 Answers0