Home > Enterprise >  C interpreting/mapping getch() output
C interpreting/mapping getch() output

Time:02-25

Consider this program:

#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
    std::string input;
    std::cin >> input;
}

The user can input any string (or single character) and the program is going to output it as is (upper/lower case or symbols like !@#$%^&* depending on modifiers).

So, my question is: what is the best way to achieve the same result using <conio.h> and _getch()? What's the most straightforward way to map the _getch() keycodes to the corresponding symbols (also depending on the current system's locale)?

What I tried was:

while (true) {
    const int key = _getch();
    const char translated = VkKeyScanA(key); // From <Windows.h>
    std::cout << translated;
}

Although this correctly maps the letters, they're all capitalized and this doesn't map any symbols (and doesn't take modifiers into account). For example:
It outputs ╜ when I type _ or -
It outputs █ when I type [ or {

A cross platform solution would be appreciated.

CodePudding user response:

The following code works:

// Code 1 (option 1)
while (true) 
{
    const int key = _getch(); // Get the user pressed key (int)
    //const char translated = VkKeyScanA(key);
    std::cout << char(key); // Convert int to char and then print it
}

// Code 2 (option 2)
while (true) 
{
    const char key = _getch(); // Get the user pressed key
    //const char translated = VkKeyScanA(key);
    std::cout << key; // Print the key
}
  •  Tags:  
  • c io
  • Related