C ++修复以检查输入是否为整数 [英] C++ Fix for checking if input is an integer

查看:225
本文介绍了C ++修复以检查输入是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我输入2a,它不会显示错误,也不会要求用户重新输入值。我如何解决这个问题?

for example, if I enter "2a", it does not show an error nor asks the user to re-input the value. how do i fix this?

while (std::cin.fail())
{ 
    std::cout << "ERROR, enter a number" << std::endl;
    std::cin.clear();
    std::cin.ignore(256,'\n');
    std::cin >> dblMarkOne;
}
std::cout << "" << std::endl;


推荐答案

两种可能的解决方案:


  1. 首先将输入存储在std :: string中,而不是直接存储到int中。然后,使用strtol from转换为整数。如果endPtr指向0,则表示结尾没有任何内容,所以这没关系。否则,最后会找到一些没有数字的字符

  2. 在您的示例中, std :: cin>> dblMarkOne; 将在 std :: cin 中保留非数字字符,因此如果 std中仍有数据可用: :cin 之后,例如使用 std :: cin.peek()!= EOF ,这意味着用户输入了多个数字。

  1. First store the input in a std::string instead of directly to an int. Then, use strtol from for converting to an integer. If the endPtr points to 0, it means nothing is left at the end, so this is OK. Otherwise, some no number characters are found at the end
  2. In your example, std::cin >> dblMarkOne; will leave non-number characters in std::cin, so if there is still data available in std::cin after, for instance by using std::cin.peek()!=EOF, this means the user has entered more than a number.

编辑:完整测试代码:

#include <iostream>
#include <cstdio>

int main(int argc, char ** argv)
{
    bool ok = false;
    int dblMarkOne;
    std::cout << "Enter a number" << std::endl;
    while (!ok)
    { 
        std::cin >> dblMarkOne;

        if(!std::cin.fail() && (std::cin.peek()==EOF || std::cin.peek()=='\n'))
        {
            ok = true;
        }
        else
        {
            std::cin.clear();
            std::cin.ignore(256,'\n');
            std::cout << "Error, Enter a number" << std::endl;
        }
    }
}

这篇关于C ++修复以检查输入是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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