检查两个单独的输入时出错

Error checking two separate inputs

我正在尝试检查两个单独的输入是否为整数。我能够对一个输入进行错误检查,但如果我使用 'get' 函数并且两个输入都来自 'cin' 流,我不太确定如何检查两个单独的输入。使用 c++.

我检查一个整数的代码如下所示。

#include <iostream>
using namespace std;

int main() {
int input;

cout << "Enter an integer: ";
cin >> input;

char next;
int x=0;

int done = 0;

while (!done){
    next = cin.get();
    if (next == ' ' || next == '\n'){
        cout << "The Integer that you have entered is: " << input << "\n";
        done = 1;
    }
    else if (next == '.'){
        cerr << "Error: Invalid Input. Not an Integer." << "\n";
        done = 1;
    }
    else{
        cerr << "Error: Invalid Input. Not a number." << "\n";
        done = 1;
    }
}

return 0;
}

好吧,您可以将 >> 一直用到 int 中,放弃所有 get() 内容和字符处理,然后检查 cin.fail()。例如(我会把它放在你的程序中并在循环中重复它作为你的练习):

int x;
cin >> x;
if (cin.fail())
    cout << "Not a valid integer." << endl;

您可以用完全相同的方式处理所有后续输入。没有理由只将 operator >> 限制为第一个输入。