0

I have gone through many existing answers here StackOverflow, but I am still stuck.

code:

int c;
cin >> c;

if(cin.fail()) {
   cout << "Wrong Input";
   cin.clear();
   cin.ignore(INT_MAX, '\n');
}
else
{
   cout << c*2;   
}

If I enter wring input e.g s instead of an integer, it outputs Wrong Input. However, if I enter an integer, and then I enter a string, it ignores the string and keep outputting the previous integer result, hence it does not clears the cin buffer, and the old value of c keeps on executing. Can anyone please suggest the best way other than cin.ignore() as it does not seem to work. and yeah for me, the max() in cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); gives error. So this does not work either.

Nix
  • 150
  • 1
  • 13
  • 1
    Why don't you ask a question to get the correct way to do this working? [This](http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) is the correct way to handle the situation. – NathanOliver Oct 12 '16 at 16:04
  • Can you make your question clearer (e.g. providing a [MCVE]). I can't spot what shouldn't work with your code. I can't get it even to [compile](http://ideone.com/Syb32Q) – πάντα ῥεῖ Oct 12 '16 at 16:11
  • @NathanOliver This gives me error `numeric_limits::max()` the max() function gives me error `#define max(a,b) (((a) > (b))) ? (a) : (b))` even if I define this statement in my file. @πάνταῥεῖ I will try to upload a video I think that might be more clear. – Nix Oct 13 '16 at 21:11
  • Do you have in your code `#define max(a,b) (((a) > (b))) ? (a) : (b))` or do you include a header that has that in it? – NathanOliver Oct 13 '16 at 21:23

1 Answers1

1

the max() function needs to be defined in the beginning of the file. cin.ignore() works very well to clear the buffer, however you need the numeric limits function max(), which in my case was giving error.

Solution:

#ifdef max
#define max
#endif

add these lines on the top, and a function such as following will work fine.

int id;
bool b;
do {
    cout << "Enter id: ";
    cin >> id;
    b = cin.fail();
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while ( b == true);

P.S: Thanks @Nathan

Nix
  • 150
  • 1
  • 13