簡體   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

出於某種原因,這只能驗證字符/字符串。 如何使其驗證負值和十進制值?

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;

您的代碼存在一些問題:

  1. 不用寫cin >> num 2次,在while循環的條件下只獲取一次輸入就夠了
  2. 不是!(cin >> num || num < 0) ,而是!(cin >> num) || num < 0 !(cin >> num) || num < 0 as !(cin >> num)將報告字符串的輸入,而num < 0將報告負值的輸入
  3. 由於輸入了一個十進制值, cin會將該值存儲到. 並留下剩余的數字. 在沒有消耗它們的緩沖區中,您可以添加條件cin.peek() == '.' 檢查用戶是否輸入了十進制值

這是您的編輯代碼:

#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;
}

這是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