【发布时间】:2020-12-24 00:27:51
【问题描述】:
这是我的代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
long int iterFunc(int);
long int recurFunc(int);
int main() {
int n;
while(true){
try{
cout << "Enter: ";
if (!(cin >> n))
throw("Type Error");
if (n < 0)
throw n;
else
if (n == 0)
break;
cout << "Iterative: " << iterFunc(n) << endl;
cout << "Recursive: " << recurFunc(n) << endl;
}
catch(int n){
cout << "Error. Enter positive number." << endl;
}
catch(...){
cin.clear();
cin.ignore(100, '\n');
cout << "Error. Please enter a number" << endl;
}
}
cout << "Goodbye!";
return 0;
}
long int iterFunc(int n){
vector<long int> yVec = {1, 1, 1, 3, 5};
if (n <= 5)
return yVec[n - 1];
else
for(int i = 5;i < n; i++){
long int result = yVec[i - 1] + 3 * yVec[i- 5];
yVec.push_back(result);
}
return yVec.back();
}
long int recurFunc(int n){
switch (n) {
case 1:
case 2:
case 3:
return 1;
break;
case 4:
return 3;
break;
case 5:
return 5;
break;
default:
return recurFunc(n - 1) + 3 * recurFunc(n - 5);
break;
}
}`
程序应该只接受一个整数并使用迭代和递归实现返回函数的 y。例如:30、59、433。如果用户输入的整数多于一个,用空格分隔,如何抛出错误消息?例如:“3 45 32”。
我尝试使用if (cin.getline == ' ') throw("Error name"),但程序仍然执行并返回输入中数字的函数的y
【问题讨论】:
-
通过
std::string和std::getline将输入读取为一行,通过std::istringstream解析该行,如果您检测到多个输入参数,请忽略整个事情,吠错误,然后继续。坦率地说,您不想支持多个输入参数的用例有点弱,但也没有很好地描述,所以这可能就是原因。 -
这并没有解决问题,但是这段代码不适合使用异常。只需使用
if ... else进行错误处理。异常适用于无法在本地处理的错误。
标签: c++ validation input error-handling c++17