I’m learning C++.
nav is an integer .
I want to ask user for typing a valid value, if he / she type an invalid value.
void main()
{
printf("Type an integer : ");
if(!scanf("%d", &nav))
{
system("cls");
printf("Invalid ! \n");
main();
}
}
But it’s blinking after typing first value . It’s blinking like reloading screen. I think it’s infinite loop.
How can i do it in right way ? I want to ask a number from users, until it’s typing a real number .
If the user types an invalid input,
scanf()won’t consume it, and you’ll be left peeking the same offending input character forever. You need to first read whatever the user enters — I recommend usingstd::getline()— and then try to parse that withstrtol(),sscanf()orstd::istringstream. Don’t useatoi()because it doesn’t report failures.EDIT: See the comments for a rather beautiful rendition of the above logic. I’ve left it out of the answer because: a) I don’t want to steal someone else’s idea, and b) I’m not sure I’d present a newcomer to C++ with that formulation — not in one go, at least.
P.S.: You can’t call
main()in C++.