do while loop error

First off here's the program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace 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.

Any ideas?
what is the "answer==5" for ?
just to test the while loop after entering the for loop (it was originally while(cin.fail()) but that just caused an infinite loops)
Last edited on
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().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using std::cin;
using std::cout;

int main()
{
    int answer;
    cin >> answer;

    if(cin.fail())
    {
        do
        {
            cout << "nope\n";
            cin.clear();
            cin.get();
            cin >> answer;
        }while(answer != 5);
    }
    else
        cout << answer;
}
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)
Last edited on
Topic archived. No new replies allowed.