Spencer Chow Spencer Chow - 1 year ago 87
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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download