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

use*_*546 13 c++ cin

我输入了这个,它要求用户输入两个整数,然后变成变量.从那里它将执行简单的操作.

如何让计算机检查输入的内容是否为整数?如果没有,请让用户键入一个整数.例如:如果有人输入"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;

}
Run Code Online (Sandbox Code Playgroud)

Che*_*tpp 27

你可以这样检查:

int x;
cin >> x;

if (cin.fail()) {
    //Not an int.
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以继续获取输入,直到获得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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:要解决以下关于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;
}
Run Code Online (Sandbox Code Playgroud)

  • `if(!cin)`有效,但它隐藏了它实际做的事情.`if(cin.fail())`做同样的事情并且更清楚. (4认同)