简体   繁体   English

C++ 输入验证整数。 num 的输入不应是字符/字符串、十进制值或负数

[英]C++ Input Validation for Whole Number. The input for num should not be a char/string, a decimal value, or a negative number

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:您的代码存在一些问题:

  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不用写cin >> num 2次,在while循环的条件下只获取一次输入就够了
  2. it's not !(cin >> num || num < 0) , it's !(cin >> num) || num < 0不是!(cin >> num || num < 0) ,而是!(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 >> num) || num < 0 as !(cin >> num)将报告字符串的输入,而num < 0将报告负值的输入
  3. since entering a decimal value, the cin will store the value till the .由于输入了一个十进制值, cin会将该值存储到. and leave the remaining digits with .并留下剩余的数字. in the buffer not consumed them, then you can add the condition cin.peek() == '.'在没有消耗它们的缓冲区中,您可以添加条件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:这是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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM