Detecting ENTER key in C++
You are several problems with your code:
you are calling
operator>>
withchar[]
buffers without protection from buffer overflows. Usestd::setw()
to specify the buffer sizes during reading. Otherwise, usestd::string
instead ofchar[]
.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 bycin >> age
without waiting for new input. To avoid that, you need to callcin.ignore()
to discard any unread data. Otherwise, consider usingcin.getline()
instead (orstd::getline()
forstd::string
), which consumes everything up to and including a linebreak, but does not output the linebreak (you should consider using this for thename
value, at least, so that users can enter names with spaces in them).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 usestd::noskipws
, but that causes an unwanted side effect when reading character data - leading whitespace is left in the input buffer, which causesoperator>>
to stop reading when it reads a whitespace character before any user input is read. So, to avoid that, you can usecin.peek()
to check for an entered linebreak before callingcin >> 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