猿问

检查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;


}


交互式爱情
浏览 557回答 3
3回答

湖上湖

您可以像这样检查:int x;cin >> x;if (cin.fail()) {&nbsp; &nbsp; //Not an int.}此外,您可以继续获取输入,直到通过以下方式获取整数为止:#include <iostream>int main() {&nbsp; &nbsp; int x;&nbsp; &nbsp; std::cin >> x;&nbsp; &nbsp; while(std::cin.fail()) {&nbsp; &nbsp; &nbsp; &nbsp; std::cout << "Error" << std::endl;&nbsp; &nbsp; &nbsp; &nbsp; std::cin.clear();&nbsp; &nbsp; &nbsp; &nbsp; std::cin.ignore(256,'\n');&nbsp; &nbsp; &nbsp; &nbsp; std::cin >> x;&nbsp; &nbsp; }&nbsp; &nbsp; std::cout << x << std::endl;&nbsp; &nbsp; return 0;}编辑:要解决以下有关10abc之类的输入的注释,可以修改循环以接受字符串作为输入。然后检查字符串中是否包含数字以外的任何字符,并相应地处理该情况。在那种情况下,不需要清除/忽略输入流。验证字符串只是数字,然后将字符串转换回整数。我的意思是,这只是袖手旁观。可能有更好的方法。如果您接受浮点数/双精度数,则此方法将无效(必须在搜索字符串中添加“。”)。#include <iostream>#include <string>int main() {&nbsp; &nbsp; std::string theInput;&nbsp; &nbsp; int inputAsInt;&nbsp; &nbsp; std::getline(std::cin, theInput);&nbsp; &nbsp; while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {&nbsp; &nbsp; &nbsp; &nbsp; std::cout << "Error" << std::endl;&nbsp; &nbsp; &nbsp; &nbsp; if( theInput.find_first_not_of("0123456789") == std::string::npos) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cin.clear();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cin.ignore(256,'\n');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; std::getline(std::cin, theInput);&nbsp; &nbsp; }&nbsp; &nbsp; std::string::size_type st;&nbsp; &nbsp; inputAsInt = std::stoi(theInput,&st);&nbsp; &nbsp; std::cout << inputAsInt << std::endl;&nbsp; &nbsp; return 0;}
随时随地看视频慕课网APP
我要回答