Detecting ENTER key in C++

You are several problems with your code:

  1. you are calling operator>> with char[] buffers without protection from buffer overflows. Use std::setw() to specify the buffer sizes during reading. Otherwise, use std::string instead of char[].

  2. cin >> name reads only the first whitespace-delimited word, leaving any remaining data in the input buffer, including the ENTER key, which is then picked up by cin >> age without waiting for new input. To avoid that, you need to call cin.ignore() to discard any unread data. Otherwise, consider using cin.getline() instead (or std::getline() for std::string), which consumes everything up to and including a linebreak, but does not output the linebreak (you should consider using this for the name value, at least, so that users can enter names with spaces in them).

  3. by default, operator>> skips leading whitespace before reading a new value, and that includes line breaks. You can press ENTER all you want, operator>> will happily keep waiting until something else is entered. To avoid that, you could use std::noskipws, but that causes an unwanted side effect when reading character data - leading whitespace is left in the input buffer, which causes operator>> to stop reading when it reads a whitespace character before any user input is read. So, to avoid that, you can use cin.peek() to check for an entered linebreak before calling cin >> age.

Try something more like this:

#include <iostream>
#include <limits>
#include <iomanip>

char name[100] = {0};
char age[12] = {0};

std::cout << "Enter Name: ";
std::cin >> std::setw(100) >> name;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
if (!std::cin.getline(name, 100))
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
*/

std::cout << "Enter Age: ";
if (std::cin.peek() != '\n')
    std::cin >> std::setw(12) >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Or:

#include <iostream>
#include <string>
#include <limits>

std::string name;
std::string age;

std::cout << "Enter Name: ";
std::cin >> name;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
std::getline(std::cin, name);
*/

std::cout << "Enter Age: ";
if (std::cin.peek() != '\n')
    std::cin >> age;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
/* or:
std::getline(std::cin, age);
*/

One way to do it is to use getline to read the input, then test the length of the input string. If they only press enter, the length of the line will be 0 since getline ignores newlines by default.

std::string myString = "";

do {
     std::cout << "Press ENTER to exit" << std::endl;
     std::getline(std::cin, myString);
} while (myString.length() != 0);

std::cout << "Loop exited." << std::endl;

Have you tried this?:

cout << "Press Enter to Continue";
cin.ignore();

also check out this question

Tags:

C++