我正在尝试编写一个关于土豆泥的程序,但我的异常处理无法正常工作。相反,我得到以下输出: 输出显示 if (DaysNumber < 7) output instead of the error message
我有以下代码(这是我的主文件;如果您也想查看这些文件,我在这个问题的底部有一个指向我的 GitHub 存储库的链接,其中包含其他文件):
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <stdexcept>
#include "tatertot.h"
using namespace std;
int main() {
int DaysNumber;
// Asks the user how long it’s been since they ate tater tots
cout << "How long has it been since you had some yummy tots?" << endl;
cout << "Enter the number of days: " << endl;
cin >> DaysNumber;
// Handles invalid inputs
try {
// If it’s been a week (or more) since the user ate tater tots…
if (DaysNumber >= 7) {
cout << "Yay! I bet those tots were delicious. Here's a recipe to try next time you want to eat tater tots: " << endl;
cout << "https://www.allrecipes.com/recipe/236749/tater-tots-nachos/";
abort();
}
// If the user ate tater tots recently…
else {
cout << "It. Is. TATER TOT TIME!" << endl;
cout << "Go enjoy some yummy tots!" << endl;
cout << "https://www.allrecipes.com/recipe/236749/tater-tots-nachos/";
abort();
}
}
catch (string e) {
cin.clear();
cout << "I'm sorry, but your input is invalid. Could you please try again?" << endl;
cin >> DaysNumber;
}
catch (double e) {
cin.clear();
cout << "I'm sorry, but your input is invalid. Could you please try again?" << endl;
cin >> DaysNumber;
}
return 0;
};
我尝试过使用其他异常处理方法并在类文件和访问器-变异器文件中定义 DaysNumber,但无济于事。也许我在这里缺少一些东西?
哦,这是我的 GitHub 存储库的链接:https://github.com/NEE64/potate-repository
您的无效输入只会导致 0 被读入变量。没有什么会引发您试图捕获的异常。
喜欢,请查看 https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt :
如果提取失败(例如,如果在需要数字的地方输入了字母),则将零写入值并设置失败位。