Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ interpreting/mapping getch() output

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading