0

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

return 0;
}
Spencer Chow
  • 115
  • 2
  • Use `std::getline` instead of `operator>>`. – Sam Varshavchik Sep 29 '16 at 01:36
  • And quit using using namespace std.. Reason? [Here](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – amanuel2 Sep 29 '16 at 01:43
  • @amanuel2 Despite that other post, there's actually no reason not to use the whole namespace in this particular case. – Jason C Sep 29 '16 at 01:52
  • @JasonC ofcourse your right for this case. But as he does bigger projects this bad practice may come back hunt him. Best to avoid it ;) – amanuel2 Sep 29 '16 at 01:56
  • @amanuel2 Never understood the tendency of folks to attempt to teach beginners overly-distilled versions of everything they'll ever need to know through comments on their questions. – Jason C Sep 29 '16 at 01:57
  • @JasonC I'm just saying it's not good practice. You think it's Good practice? – amanuel2 Sep 29 '16 at 02:04
  • 1
    @amanuel2 @ JasonC thank you both for your inputs on using the namespace std or not in this situation. I understand why it is not a good practice but my prof said for the time being it is best to use it since we are just learning the basics of coding in c++. – Spencer Chow Sep 29 '16 at 02:07

1 Answers1

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.

Community
  • 1
  • 1
Jason C
  • 38,729
  • 14
  • 126
  • 182