There are several problems here.
Firstly, as @jrd1 has linked, the way you cast cin>>n
is incomplete. Your program's function appears to require some kind of validation, but cin
fails if the input is not numeric (see the use of cin.fail()
in integer input validation, how? and Integer validation for input). You must check if cin
has failed, and refresh cin
for the next round of input.
One of your if
statement and while
statement is redundant, since n
does not change between the evaluation of while
and if
on the subsequent loop.
Since you must check if cin
has failed, there is no need to additionally check isdigit(n)
. That is, if cin
did not fail, then n
must be a digit.
Your continue
statement is redundant. continue
skips to the end of the loop, but this is not necessary since all the remaining code is in the else
block, hence there is nothing to skip over. This is only useful if you want to skip any code after your if
block (which your code doesn't have).
Your intention with the else
block appears to indicate a successful validation. You may consider using a break
statement, which breaks the code execution out of the current loop.
Once you take into account of all of these, you will arrive at something like @R-Sahu's code.
This is an example that most closely resembles your code:
#include <iostream>
using namespace std;
int main() {
int n;
do {
cout<<"Enter an integer number\n";
cin>>n;
if(cin.fail()) {
cout << "Wrong Input" <<endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} else {
break;
}
} while (true);
cout<<"Good Job\n"<<endl;
}
Here is another example that is "more" streamlined, and does not require break
or continue
statements (stylistic choices for better "readable" code by some programmers)
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter an integer number\n" << endl;
cin>>n;
while ( cin.fail()){
cout << "Wrong Input. Enter an integer number\n" <<endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin>>n;
}
cout<<"Good Job\n"<<endl;
}
EDIT: fixed a problem in the second example where ! cin>>n
was not behaving as expected.
EDIT2: fixed a problem in the first example where isdigit
was incorrectly applied. See R Sahu's explanation.