key press

Good afternoon, my program is running on a while loop close to infinite, and i need program to do something if user presses letter 'k'. I do not want the program to wait for an input i just want it to run real time and if a user presses 'k' it does something. Do you have any ideas or where i could read upon it?
You'd probably need something platform- specific. For example, does your program run on Windows or Linux or Mac or ...?
It runs on Windows. Microsoft Visual Studio 15
Last edited on
Well, this is non-standard, but should run on a Windows system
Press the escape key to exit from the loop. Press k to see the message at line 30 displayed.

(Use of Sleep() here was just for this example, and isn't strictly necessary).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <conio.h>
#include <windows.h>

const int key_K = 0x4B;

int keypress()
{
    if (_kbhit())
    {
        int temp = _getch();
        if (temp == 0 || temp == 0xE0)  // special keys such as arrow or function
            temp = _getch() + 0x100;    // make it distinguishable from ordinary key
        return temp;
    }
    return 0;
}

int main() 
{
    for (int i=0; i<10000; ++i)
    {
        std::cout << i << '\n';
        
        int key = keypress();


        if (key == 'K' || key == 'k' )
        {
            std::cout << "K key was pressed\n";
        }
         
            
        if (key == 27) // test for ESCape key
            break;
            
        Sleep(250);    
    }
    
    std::cout << "Escape key was pressed\n";
}



There are other approaches, using GetKeyState or GetAsyncKeyState.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx

One way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
  while (true)
  {
    // do some stuff here like
    cout << '.';
    if (_kbhit() && _getch() == 'k')
    {
      // so sth else
      break;
    }
  }
  system("pause");
  return 0;
}
It works exceptionaly! Thank you guys so much!
Topic archived. No new replies allowed.