Spencer Chow Spencer Chow - 4 months ago 44
C++ Question

Error checking two separate inputs

I'm trying to check two separate inputs if they are integers or not. I'm able to error check one input but I'm not quite sure how to check two separate ones if I'm using the 'get' function and both inputs are from the 'cin' stream. Using c++.

My code for checking one integer is displayed below.

#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;
cerr << "Error: Invalid Input. Not a number." << "\n";
done = 1;

return 0;


Well you could use >> into an int all the way through, drop all that get() stuff and character handling, and check cin.fail(). For example (I'll leave working this into your program and repeating it in a loop as an exercise for you):

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

You can handle all subsequent input in exactly the same way. There's no reason to only limit operator >> to the first input.