检查cin输入流产生一个整数 [英] Checking cin input stream produces an integer

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

问题描述

我正在键入此字符,它要求用户输入两个整数,这些整数随后将成为变量。从那里将执行简单的操作。

I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.

如何让计算机检查输入的内容是否为整数?如果不是,则要求用户输入一个整数。例如:如果有人输入 a而不是2,它将告诉他们重新输入数字。

How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.

谢谢

 #include <iostream>
using namespace std;

int main ()
{

    int firstvariable;
    int secondvariable;
    float float1;
    float float2;

    cout << "Please enter two integers and then press Enter:" << endl;
    cin >> firstvariable;
    cin >> secondvariable;

    cout << "Time for some simple mathematical operations:\n" << endl;

    cout << "The sum:\n " << firstvariable << "+" << secondvariable 
        <<"="<< firstvariable + secondvariable << "\n " << endl;

}


推荐答案

您可以像这样检查:

int x;
cin >> x;

if (cin.fail()) {
    //Not an int.
}

此外,您可以继续获取输入,直到通过以下方式获得整数为止: / p>

Furthermore, you can continue to get input until you get an int via:

#include <iostream>



int main() {

    int x;
    std::cin >> x;
    while(std::cin.fail()) {
        std::cout << "Error" << std::endl;
        std::cin.clear();
        std::cin.ignore(256,'\n');
        std::cin >> x;
    }
    std::cout << x << std::endl;

    return 0;
}

编辑:要解决以下有关10abc之类的输入的注释,可以修改循环以接受字符串作为输入。然后检查字符串中是否包含数字以外的任何字符,并相应地处理该情况。在那种情况下,不需要清除/忽略输入流。验证字符串只是数字,然后将字符串转换回整数。我的意思是,这只是袖手旁观。可能有更好的方法。如果您接受浮点数/双精度数(在搜索字符串中必须添加。),则此方法将无效。

To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).

#include <iostream>
#include <string>

int main() {

    std::string theInput;
    int inputAsInt;

    std::getline(std::cin, theInput);

    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

        std::cout << "Error" << std::endl;

        if( theInput.find_first_not_of("0123456789") == std::string::npos) {
            std::cin.clear();
            std::cin.ignore(256,'\n');
        }

        std::getline(std::cin, theInput);
    }

    std::string::size_type st;
    inputAsInt = std::stoi(theInput,&st);
    std::cout << inputAsInt << std::endl;
    return 0;
}

这篇关于检查cin输入流产生一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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