如何验证整数输入 [英] How can I validate an integer input

查看:59
本文介绍了如何验证整数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下代码:

#include <iostream>
using namespace std;

int main()
{
    int test = 0;
    cout << "Please input a number:";

    while(!(cin >> test))
    {
        cout << "Invalid input";
    }

    if(test  == 1)
    {
        cout << "Test is 1";
    }
    else
    {
        // Do something
    }
   return 0;
}

如果我向测试变量输入 1abc ,即使输入错误,它仍继续处理 if 语句.我怎么能忽略所有输入,只接受其中的纯数字?

If I input 1abc to the test variable it still continues to process the if statement even though the input is wrong. How could I ignore all the input made and just accept pure numbers in it?

推荐答案

您可以使用 getline find_if_not isdigit 来检查是否整行是否为有效整数.这将循环直到读取整数:

You can use getline, find_if_not, and isdigit to check if an entire line is a valid integer or not. This will loop until it reads an integer:

std::string number;
while (std::getline(std::cin, number) && number.end() !=
       std::find_if_not(number.begin(), number.end(), &isdigit))
    std::cout << "gitgud!";

getline 将读取输入直到换行符,并将其放入字符串中. find_if_not isdigit 将找到第一个非数字字符.如果不存在(意味着它是一个有效的整数),它将返回 end 迭代器.

getline will read the input up to the newline, and put it in the string. find_if_not and isdigit will find the first non-digit character. If there are none (meaning it is a valid integer), it will return the end iterator.

这篇关于如何验证整数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆