I’m trying to return a question if user inserts an invalid input using C++. I’m using goto statement but the problem is it keeps looping the question over and over again not allowing the user to input anything in the command prompt.
Here’s my code:
#include <iostream>
#include <cmath>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int human_years, dog_per_human_age, dog_years;
starthere:
cout << "How many years ago did you buy your dog?" << endl;
cin >> human_years;
if (cin.fail() || std::isnan(human_years))
{
cout << "Non numerical value inserted! Please try again.n";
goto starthere;
}
else {
dog_per_human_age = 5;
dog_years = human_years * dog_per_human_age;
cout << "Your Dog is " << dog_years << " years old.";
return 0;
}
}
[Invalid Input SnippetValid input snippet](https://i.sstatic.net/bZWKz3sU.png)
I’m trying to return a question if user inserts an invalid input using C++. I’m using goto statement but the problem is it keeps looping the question over and over again not allowing the user to input anything in the command prompt.
David Orizu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.