#include <iostream>
usingnamespace std;
int main()
{
int answer;
cin>>answer;
if(cin.fail())
{
do
{
cout<< "nope\n";
cin>>answer;
}while(answer==5);
}
else
cout<<answer;
}
The program should accept some input and store it into the variable 'answer'. If the input fails (i.e. it's not an integer such as the letter 'f') then it executes the do while loop.
The problem is that when you enter in 'f', it displays "nope" but doesn't ask for a new input.
I answered in your other post, then I stumbled onto this, lol.
I am assuming that if the user enters a 5, you want it to exit the do-while? The problem is in the conditional on your do-while. You have it set to "loop this if answer is equal to 5". I believe you want to change it to not equals? Anyway, if that is true, there is one other thing you need to do, you need to flush the input stream. The easiest way I can think of, I added to the code below. It just consists of cin.clear() and cin.get().
Haha sorry Callmecrazy. I meant to delete the post in C++ beginners after re-posting but i forgot.
The while(answer == 5) was just a test to see if the while loop was working (which it wasn't). I tried using just cin.clear() and it wasn't working. All I need was cin.get() I guess! :D
IF you could, would you mind telling my why having just cin.clear() and then cin>>answer doesn't work? One would think that using cin.clear() to flush the input and then asking for a new input would work.
I really don't know why. I just knew that the input stream had to be flushed, so I googled it to try and find a very simple way. However, I know that cin.get() is a way to pause it. I can't really make a good guess without knowing what cin.clear() and cin.get() actually do (aside from the "this is what happens when you use this function)