Hello there, I'm trying to detect when the enter key is pressed to break an input loop as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
string words[100];
int i = 0;
bool checkEnter = true;
do {
cin >> words[i];
if ((words[i].empty()) && (i>1)) {
checkEnter = false;
break;
}
i++;
} while (checkEnter);
return 0;
}
But the program doesn't end when I press enter without inputting anything (even after I've inputted a few words already). Anyone know what I'm doing wrong?
Guys I'm not ignorant, I've been trying to solve this for a couple hours, and have searched around heaps. The problem with the topic you linked is that the second poster either uses cin.get() or empty(). I don't want to use cin.get() because I need the user to input an entire word (if he/she hasn't finished typing in words) and store it into a string array. I also don't want to use getline because I want the user to input a single word only. And so I am trying the empty function and using cin yet it's not working.
EDIT: If I am wrong and that topic does show what I'm trying to do (apologies, I didn't understand it since I'm not acquainted with all the things he used) then please explain why my program doesn't work.
You are trying to do something at odds with the way things work.
(1) You want to input a word, bounded by any throwaway whitespace
(2) You want to test whether the user only pressed a specific whitespace character
Your options are to use cin.get() to read a character-by-character and build your word that way, or to use std::getline() and s.empty() and then a std::istringstream to break the line into individual words (which is exactly what the second example does, except with integers instead of words).
cin >> anything; will gobble up any leading whitespace, so you won't be able to detect just an Enter key press with it.
So, we're going to have to do things slightly differently:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter something (or nothing): ";
std::string input;
if (std::cin.peek() == '\n') // Peek at the next character (stops for input if there is none)
std::cout << "You entered nothing. Why'd you do that?!";
else
{
// Now actually get the input
std::cin >> input;
std::cout << "You entered: " << input;
}
}
If you put this in a loop, you'll also want to #include <limits> and put a std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after the std::cin >> input; line; otherwise, it'll leave a newline in the input buffer afterwards and that will get picked up by std::cin.peek() in the next iteration instead of any new input you might have.