C++ keypress: getch, cin.get?

前端 未结 6 1106
逝去的感伤
逝去的感伤 2020-12-15 16:48

I have a Win32 program that runs on a loop. I would like to be able to pause that program while awaiting a keypress. It doesn\'t matter whether I use \'any key\' or a specif

相关标签:
6条回答
  • 2020-12-15 16:48
    HWND hwnd = ::GetConsoleWindow();
    
    while (!((::GetForegroundWindow() == hwnd) &&
            ((::GetKeyState(VK_SPACE) & 0x8000) != 0)))
        ::Sleep(0);
    

    Suppose it is not the best way but it solved my problem. Replace VK_SPACE with any other value you like. And it is not portable.

    0 讨论(0)
  • 2020-12-15 16:56

    Assuming that you are looking for an alternative for getch ( which does not echo to screen).

    If you are using windows and visual studio to be precise try using _getch. Here is a link to it http://msdn.microsoft.com/en-us/library/078sfkak(v=VS.100).aspx

    0 讨论(0)
  • 2020-12-15 17:02

    Example:

    #include <iostream>
    #include <conio.h>
    
    int main()
    {
      std::cout << "Press any key to continue . . ." << std::endl;
      _getch(); // wait for keypress
    }
    

    _getch() is C++ equivalent to C getch()

    0 讨论(0)
  • 2020-12-15 17:07

    You should use neither.

    You should use

    #include <iostream>
    ...
    int main()
    {
       ... 
       std::cin.ignore(); //why read something if you need to ignore it? :)
    }'
    

    Here's the documentation

    0 讨论(0)
  • Try

    #include <iostream>
    
    using namespace std;
    
    char temp;
    cin >> temp;
    
    0 讨论(0)
  • 2020-12-15 17:12

    You should #include <iostream> and use std::cin.get();

    I think the getch() is a C function, but since you are using C++, then the cin would be more appropriate.

    0 讨论(0)
提交回复
热议问题