Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ keypress: getch, cin.get?

Tags:

c++

keypress

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 specific key, but I need to have the program freeze until I press something.

I am wondering which command I should use. I am working with Visual C++ and the compiler doesn't recognise any of the following commands:

cin.get()

std::cin.get()

getch()

I am relatively new to C++. I understand that in a console app this is a fairly simple action to take (cin.get), but that it can be more difficult in Win32. Any simple solution or workaround would be appreciated. The program is bespoke to be used in a single scientific experiment, so for now I'm not fussed if the solution is a little botchy(!)

Apologies if I've missed any important info from my question.

like image 990
CaptainProg Avatar asked Aug 10 '11 12:08

CaptainProg


4 Answers

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

like image 79
Armen Tsirunyan Avatar answered Oct 17 '22 18:10

Armen Tsirunyan


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

like image 42
Daniel Blom Avatar answered Oct 17 '22 17:10

Daniel Blom


Try

#include <iostream>

using namespace std;

char temp;
cin >> temp;
like image 3
Jason Avatar answered Oct 17 '22 17:10

Jason


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

like image 2
xeon111 Avatar answered Oct 17 '22 18:10

xeon111