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;
}
}
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.
Even I strongly recommend not to use goto
, but if you really want to use the same you can just add cin.clear
and cin.ingnore(1000,'\n')
before calling the goto
statement. What it does is it clears the buffer up to the character that you want. (The 1000 is put there to skip over a specific number of chars before the specified delimiter, in this case, the '\n'
newline character.)
#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";
cin.clear();
cin.ignore(1000,'\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;
}
}