I've written some code to detect empty user input:
if(cin.get() == '\n')
{
cout<<"ENTER WAS PRESSED"<<endl;
}
But for some reason if the user presses ENTER it just keeps advancing to the next line as I press ENTER.
I've written some code to detect empty user input:
if(cin.get() == '\n')
{
cout<<"ENTER WAS PRESSED"<<endl;
}
But for some reason if the user presses ENTER it just keeps advancing to the next line as I press ENTER.
I think this code does your job.
AFAIK, I think that you shouldn't use the
get()
function to input numbers. Theget()
function is designed to input characters and it behaves as an Unformatted Input Function. The>>
operator seems better for this job. The extraction operator>>
will wait for your input if you press the ENTER key because it will ignore it. However, the newline input is stored in thecin
input stream. You can also try a combination of thepeek()
and theseekg()
function to check for an existing newline input in the input stream and do what you want.In this form your code works for me:
However, your further comments reveal that your code also includes this:
There is your trouble.
What you are trying will not work with that particular
while
, but many first-term students of C++ ask similar questions, so let me explain. The reason that it will not work is that your concept ofstd::cin
is vague. (By the way,std::cin
, please, orcin
preceded byusing std::cin;
if you must. The textbook that is telling you to issueusing namespace std;
should be burned.)The object
std::cin
is a stream—from your perspective, a queue from which your program can accept available input characters when it wishes to do so. Important:std::cin
is not a command or an operation, but an object called a stream. By analogy with speech, you may be thinking ofstd::cin
as a verb, only it isn't: it is a noun. By itself,std::cin
does not do anything.What does do something is the extraction operator
>>
. What also does something is the single-character fetching member function.get()
. Both of these retrieve previously unseen characters from the streamstd::cin
. So, the>>
retrieves some characters which the program puts intonumber
, then tests. Then the.get()
retrieves another, previously unseen character, which the program checks to see whether it is a newline. But why does your program treat the former group of characters as a possible number and the latter, single character as a possible newline? How does it know that the former group of characters does not begin with a newline?My suggestion is to try some simpler test programs for a while, using either
>>
or.get()
, but not both in the same program. For now, using both at once is understandably confusing you. Stream input can be tricky. You are unlikely to benefit from further explanation until you get this point straight in your mind, and that will probably take you an hour of trial and experiment. Good luck.