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;
there are some problems with your code:
cin >> num
2 times, it's only enough to get the input only once in the condition of the while loop!(cin >> num || num < 0)
, it's !(cin >> num) || num < 0
!(cin >> num) || num < 0
as !(cin >> num)
will report the input of string while num < 0
will report the input of negative value 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 valuethis 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.