我需要的是不接受小数的绝对方法,或者是否有一个不接受小数和字母的函数
#include <iostream>
#include <limits>
#include <cmath>
using namespace std;
double checkInput(double pagkain)
{
do
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (floor(pagkain) != pagkain || pagkain >= 51)
{
cout << "Invalid Input, We do not aceept letters or decimals. \nPlease try again: ";
}
}while (floor(pagkain) != pagkain || (pagkain >50));
return pagkain;
}
答案 0 :(得分:0)
由于您只需要整数,因此可以安全地将数据类型更改为int
而不是double
。
接下来,您可以将其作为字符串阅读并验证其正确性。
你可以这样做:
int GetValidInteger(int lowerBound, int upperBound){
string result;
while(true){
getline(cin, result);
bool valid = true;
for(int i = 0; i < result.size(); i++){
if(!isdigit(result[i])){
valid = false;
break;
}
}
if(!valid){
cout << "Only integers are accepted. Try again...\n";
continue;
}
int intResult = stoi(result);
// Outside this loop, you know that you have a valid integer.
// You can check now for your other constraints.
if(intResult < lowerBound || intResult > upperBound)
cout << "Input should be between " << lowerBound << " and " << upperBound << ". Try again...\n";
else
return intResult;
}
}
您可以使用该功能获取所需范围内的有效输入。要获得1-5范围内的订单,请执行以下操作:
int order = GetValidInteger(1,5);
如果您希望输入在1-50范围内,则相同。