[Tips]How to detect “Enter Key” pressed in C/C++?

GOAL

To detect enter key pressed in C/C++ program.

Environment

Windows 10
Visual Studio 2017

Method

Method 1. get char

If you just detect enter key pressed at any time, use getchar() or cin.get() function.

C language

#include <stdio.h>
#include <windows.h> // for Sleep function

int main(void)
{
	while(true){
		if (getchar() == '\n') {
			printf("Enter key is pressed");
			Sleep(1000); //wait for check printed message.
			break;
		}
	}
	return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
	while (1) {
		if (cin.get() == '\n') {
			cout << "Enter key is pressed" << endl;
			break;
		}
	}
	return 0;
}

Method 2. get line

If you’d like to detect that only enter key is pressed without input another key before enter, use scanf() , fgets() or gets() in C language or getline() in C++

C language

#include <stdio.h>
#include <string.h>
#include <windows.h> // for Sleep function

int main(void)
{
	while (1) {
		//if (getchar() == '\n') {
		char str[32];
		gets(str);
		if(strcmp(str,"")==0){
			printf("Enter key is pressed");
			Sleep(1000); //wait for check printed message.
			break;
		}
	}
	return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
	string str;
	while (1) {
		getline(cin, str);
		if (str == "") {
			cout << "Enter key is pressed" << endl;
			break;
		}
	}
	return 0;
}

Method 3. GetKeyState

GetKeyState() is only provided on Windows. You can get the current “state” of the key. It returns 0 when the key is not pressed.

The key code is here.

#include <iostream>
#include <windows.h> // for GetKeyState function
using namespace std;

int main() {
	cout << "some process here" << endl;
	while (1) {
		if (GetKeyState(VK_RETURN) < 0) {
			cout << "Enter Key is Pressing" << endl;
		}
		else if (GetKeyState(VK_ESCAPE) < 0) {
			break;
		}
	}
	return 0;
}