如果用户使用 C++ 插入无效输入,我会尝试返回问题。我正在使用 goto 语句,但问题是它不断循环问题,不允许用户在命令提示符中输入任何内容。
这是我的代码:
#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;
}
}
如果用户使用 C++ 插入无效输入,我会尝试返回问题。我正在使用 goto 语句,但问题是它不断循环问题,不允许用户在命令提示符中输入任何内容。
我强烈建议学习编程时不要使用 goto。 goto 的存在是程序结构错误的标志。在学习使用 goto 之前,先学会不使用它。
#include <iostream>
#include <cmath>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int human_years, dog_per_human_age, dog_years;
cout << "How many years ago did you buy your dog?" << endl;
cin >> human_years;
while (cin.fail() || std::isnan(human_years));
{
cin.clear();
cout << "Non numerical value inserted! Please try again.\n";
cin >> human_years;
}
dog_per_human_age = 5;
dog_years = human_years * dog_per_human_age;
cout << "Your Dog is " << dog_years << " years old.";
return 0;
}