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:
- Variables, Const, Datatypes & Operations
- Logical operators and comparison operators
- control structures & loops
- functions
#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:
You are not checking to make sure the user enters a valid integer.
If they do not enter a valid integer,
operator>>
will putcin
into an error state that you are not clearing. That will then causeoperator>>
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):