do while loop failure

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
#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?
Last edited on
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;
}
Last edited on
http://www.parashift.com/c++-faq/stream-input-failure.html

You should also check the next couple of faqs.
Topic archived. No new replies allowed.