我有一个程序,简单地计算阿克曼功能:CIN服用无效的输入
#include <iostream>
// Ackermann function calculations
unsigned int ackermann(unsigned int m, unsigned int n){
if(m == 0)
return n+1;
if(n == 0)
return ackermann(m-1,1);
return ackermann(m-1,ackermann(m,n-1));
}
// Check for non-integer input
bool inputCheck(){
if(!std::cin.fail())
return false;
std::cout << "Invalid input!" << std::endl;
return true;
}
// Check for negative or overflow errors
bool numCheck(int i, char name){
if(i < 0){
std::cout << "Negative error!" << std::endl;
return true;
}
if(name == 'm' && i > 3){
std::cout << "Overflow error (m > 3)!" << std::endl;
return true;
}
if(name == 'n' && i > 12){
std::cout << "Overflow error (n > 12)!" << std::endl;
return true;
}
return false;
}
// Run input and num checks
bool check(int x, char y){
bool result = inputCheck() || numCheck(x, y);
std::cin.clear();
std::cin.ignore();
return result;
}
int main(){
int m, n;
bool valM, valN;
do{
std::cout << "m = ";
std::cin >> m;
valM = check(m, 'm');
} while(valM);
do{
std::cout << "n = ";
std::cin >> n;
valN = check(n, 'n');
} while(valN);
std::cout << "\nM = " << m << "\nN = " << n
<< "\n\nCALCULATING..." << std::endl;
std::cout << "A(" << m << ',' << n << ") = " << ackermann(m,n) << std::endl;
return 0;
}
大部分代码是检查无效的输入。出于计算原因,m
不能大于3,并且n
不能大于12.它还检查输入是否为负值。
已知问题:
如果用户输入类似
3z
。 cin只需要3并忽略z。显然,3z
是不同于3
,我想检测这种无效输入。如果用户输入类似
1.2
的东西。 cin以1为m,然后以n为2。该计划忽略了这段时间,并将其作为两个输入,我想检测这种无效输入。
如何修改或修复我的代码,以便它只需要正确的输入?
你能解释一下你应该为''3z''发生什么? “z”代表什么? – nathanesau
@nathanesau程序只能接受整数输入。当输入'3z'(或类似的)时,它忽略了'z'并且像'z'这样不存在的'3'。从某种意义上说,我希望它能检测到这样一个无效的输入(像'3z')。 – esote