如何只允许用户输入正整数

How to allow only positive integer input from user?

本文关键字:用户 输入 整数 许用户      更新时间:2023-10-16

我一直试图只允许正整数输入到我的程序中。但有效的方法是通过字符输入和负整数十进制数。有什么办法解决的吗?

#include <iostream>
using namespace std;
int main()
{
int row, col, i, i1, j, test;
double n;
test = 0;
while (test == 0) 
{
cout << "Enter the number of rows: " << endl;
cin >> row;
if (cin.fail() || row <= 0 || !(row == (int)row)) 
{
cout << "nEntered value is wrong!";
printf("n");
cin.clear();
cin.ignore();
test = 0;
}
else {  test = 1;  }
}
}

我一直试图只允许将正整数输入到程序

如果您将用户输入作为字符串而不是整数,您可以在std::isdigit的帮助下轻松检查它。

  1. 将用户输入作为字符串
  2. 对于字符串中的每个字符,检查它是否是一个数字(使用std::isdigit(
  3. 如果用户输入中的任何字符(字符串(不是有效数字,则返回布尔值=false
  4. 如果所有字符都为true,则输入是一个整数,您可以使用std::to_string将其转换回整数

以下是示例代码:观看直播

#include <iostream>
#include <cctype> // std::isdigit
#include <string>
#include <vector>
bool isInteger(const std::string& input)
{
for (const char eachChar : input)
if (!std::isdigit(eachChar))
return false;  // if not a digit, return  False
return true; 
}
int main()
{
std::vector<std::string> inputs{ "123", "-54", "8.5", "45w" }; // some inputs as strings
for(const std::string& input: inputs)
{
if (isInteger(input))
{
// apply std::stoi(input) to convert string input to integer
std::cout << "Input is a valid integer: " << input << std::endl;
}
else {  std::cout << input << " is not a valid integer!n"; }
}
}

输出

Input is a valid integer: 123
-54 is not a valid integer!
8.5 is not a valid integer!
45w is not a valid integer!

这可能是您想要的(演示(:

#include <iostream>
#include <limits>
int main()
{
using namespace std;
int n;
while ( !( cin >> n ) || n < 0 )
{
cin.clear();
cin.ignore( numeric_limits<std::streamsize>::max(), 'n' );
}
//...
return 0;
}