为了账号安全,请及时绑定邮箱和手机立即绑定

检查cin输入流产生一个整数

检查cin输入流产生一个整数

C++
交互式爱情 2019-10-11 13:57:11
我正在键入它,它要求用户输入两个整数,然后将它们变成变量。从那里将执行简单的操作。如何让计算机检查输入的内容是否为整数?如果不是,则要求用户输入一个整数。例如:如果有人输入“ a”而不是2,它将告诉他们重新输入数字。谢谢 #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;}
查看完整描述

3 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

您可以像这样检查:


int x;

cin >> x;


if (cin.fail()) {

    //Not an int.

}

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


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


#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;

}


查看完整回答
反对 回复 2019-10-11
  • 3 回答
  • 0 关注
  • 520 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信