Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an empty int input?

Tags:

c++

input

I am trying a coding Q and am looking for a line of code that detects if there was no input given (user just presses enter). The concerned datatype is int.

I've read few other Qs about this very problem, but didn't fit in well with my needs. I have tried eof & other such suggestions to no avail...

Here's the code -

#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int main() {
int ogv,cgv=0,i,j=0,k;
int arr [3];
vector<int> ans;
while(true) {
    cgv=0;
    cin>>ogv;
    //if("ogv is not a number, just an enter") 
          break;
    arr[0]=floor(ogv/4);
    arr[1]=floor(ogv/3);
    arr[2]=floor(ogv/2);
    for(i=0;i<=2;i++) {
        if (arr[i]<0)
            arr[i]=0;
        cgv+=arr[i];
    }

    if(ogv>cgv) {
        ans.push_back(ogv);
    }
    else {
        ans.push_back(cgv);
    }
   j++;
}
for(k=0;k<j;k++) {
    cout<<ans.at(k)<<endl;
}
}

Your help is greatly appreciated...! :D

Thanks


1 Answers

You can use the noskipws manipulator

Example:

int x = -1;
cin>>noskipws>>x;
if(x==-1)
{
    // no number was entered, the user just pressed enter
}
else
{
    // the user entered a number
}


EDIT: In order to use this in a loop, you need to discard the characters that are currently in the buffer before each read attempt.

For example, if the user inputs the number 4 and presses enter in the first iteration of the loop, cin will read the 4, but it will leave the end-of-line character in the buffer. When the read occurs in the second iteration, cin will see the end-of-line character in the buffer and it will treat it as if the user pressed enter, exiting the loop.

We can use the sync() method in order to discard any unread characters in the buffer. We need to do this before any attempt to read from cin:

cin.sync();
cin >> noskipws >> x;
like image 79
Ove Avatar answered Jan 25 '26 02:01

Ove