LostSicilian
LostSicilian

Reputation: 1

cin is not working in a Do..While loop, program is crashing directly after start

I'm a C++ beginner, and I got stuck at a self training.

I want to do a number guessing game - pretty easy task, basically.

The issue appears in the do..while loop. I want to read in a number from the user until the right one is guessed. When I start the program, it crashes because it's always looping the cout and cin but it should wait at cin until there is an input. Why does this happen? If I would do a program just with one try, the program is waiting, until there is an input.

So, my thought was to do a do..while loop, because I want at least to go through one time.

I would appreciate some input so I can do more research about this issue.

In my training, I have done:

#include <iostream>

using namespace std;

int main()

{
    int eingabe = 0;
    int randomZahl = 8;
    bool checker = true;

    cout << "Number Guesser\n\n";

    do
    {
        if(eingabe != randomZahl)
        {
            cout << "Bitte gib eine Zahl ein: ";
            cin >> eingabe;
        }

        if(eingabe == randomZahl)
        {
        checker = false;
        }


    }while(checker);

    return 0;

}

This is how the crash looks:

image

Upvotes: 0

Views: 72

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597325

You are not checking to make sure the user enters a valid integer.

If they do not enter a valid integer, operator>> will put cin into an error state that you are not clearing. That will then cause operator>> to stop waiting for subsequent input, causing your loop to run forever.

Try this instead (forgive me if the German is wrong, I used Google Translate):

#include <iostream>
#include <limits>
using namespace std;

int main()
{
    int eingabe, randomZahl = 8;

    cout << "Number Guesser\n\n";

    do
    {
        cout << "Bitte gib eine Zahl ein: ";
        if (cin >> eingabe)
        {
            if (eingabe == randomZahl)
            {
                cout << "Du hast richtig geraten!\n";
                break;
            }

            cout << "Du hast falsch geraten! Versuchen Sie es erneut.\n";
        }
        else
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');

            cout << "Sie haben falsche Daten eingegeben! Versuchen Sie es erneut.\n";
        }
    }
    while (true);

    return 0;
}

Upvotes: 2

Related Questions