0

I need a user to enter a positive integer. Is there a way to validate that the entry was an int? This is what I have, however, if I enter a floating point number (eg: 18.5) then it doesn't handle the error correctly. However, if I enter something -5 it works fine and if I enter a char (eg: R) it also works fine. Can anyone help me understand why the FP doesn't work correctly? val1 is declared as an int and initialized to 1.

    cout << "Please enter your first value (positive integers only)" << endl;
    cin >> val1;
    while (val1 <= 0 || !cin.good()) {              // This line plus next 5 lines are user validation to ensure the first value is ONLY a positive integer
        cin.clear();
        cin.ignore();
        cout << "Invalid Entry" << endl;
        cout << "Please re-enter your first value (positive integers only)" << endl;
        cin >> val1;
}

1 Answers1

0

It's not a piece of cake to determine if a input is integer.

Your code can determine if an input is a number(float is number to). Here is my code to determine if an input is integer:

#include <iostream>
 using namespace std;
 int main() {

     int val1;
     char next;
     cin >> val1;
     cin.get(next);
     if(!cin.good() || !isspace(next) || val1 < 0)
     {
         cout << "not integer" << endl;
     }
 }

next contain the next char after a integer, if user input a float, next will be '.'

Tianxu
  • 61
  • 5