Home > Net >  C Input Validation for Whole Number. The input for num should not be a char/string, a decimal valu
C Input Validation for Whole Number. The input for num should not be a char/string, a decimal valu

Time:09-27

for some reason this only gets validation for char/string. How to make it validate negative and decimal values?

cout << "Please enter a whole number: ";
while (!(cin >> num || num < 0)){ 
    cin.clear();
    cin.ignore(10000, '\n');
    cout << "Invalid! A whole number is positive and an integer.     \n";
    cout << "Please enter a whole number again: ";
    cin >> num;

CodePudding user response:

there are some problems with your code :

  1. no need to write cin >> num 2 times , it's only enough to get the input only once in the condition of the while loop
  2. it's not !(cin >> num || num < 0) , it's !(cin >> num) || num < 0 as !(cin >> num) will report the input of string while num < 0 will report the input of negative value
  3. since entering a decimal value , the cin will store the value till the . and leave the remaining digits with . in the buffer not consumed them , then you can add the condition cin.peek() == '.' to check if the user entered a decimal value

this is the edited code of yours:

#include <iostream>

using namespace std;

int main() {
    int num = 0;
    cout << "Please enter a whole number: ";
    while (!(cin >> num) || num < 0 || cin.peek() == '.') {
        cin.clear();
        cin.ignore(10000, '\n');
        cout << "Invalid! A whole number is positive and an integer.     \n";
        cout << "Please enter a whole number again: ";
    
    }

    return 0;
}

and this is some example output:

Please enter a whole number: asdasd
Invalid! A whole number is positive and an integer.
Please enter a whole number again: -12312
Invalid! A whole number is positive and an integer.
Please enter a whole number again: 1.23
Invalid! A whole number is positive and an integer.
Please enter a whole number again: -123.2
Invalid! A whole number is positive and an integer.
Please enter a whole number again: 123

C:\Users\abdo\source\repos\Project55\Debug\Project55.exe (process 31896) exited with code 0.
  • Related