簡體   English   中英

C ++中的整數輸入驗證

[英]Integer Input Validation in C++

我對C ++中的輸入驗證有疑問。 這是我遇到麻煩的代碼:

#include <iostream>
using namespace std;

int main()
{
    int in;

    while(true)
    {
        if(cin >> in)
        {
            if(in < 0 || in > 2)
            {
                cout << "Invalid input.  Number needs to be 0, 1, or 2.";
                cin.clear();
                while(cin.get() != '\n');
                cin.ignore();
            }
            else
            {
                cout << "Output: " << in;
                break;
            }
        }
        else
        {
            cout << "Invalid input. Please enter a number.";
            cin.clear();
            while(cin.get() != '\n');
            cin.ignore();
        }
    }
}             

除非用第二個輸入形式“ 12hfhd”連續輸入兩個無效條目,否則此代碼行之有效。 然后它接受此作為輸入,但我不知道為什么。 我在SO上進行搜索,發現了許多有關輸入驗證的問題,但似乎找不到任何有關接受某些輸入的代碼的問題。

主要的問題是,當使用>>運算符從std::cin請求一個int將從輸入開始的一系列數字字符轉換。 例子:

  • 2將轉換為2
  • 75$將轉換為75
  • 12asdfgh將轉換為12
  • hello,world將轉換為0 ,因為第一個字符已經不是數字

最好的辦法是使用一些char操作:

int getNumber() {
  char input;
  std::cin >> input;
  if(input > '2' || input < '0') { // yes, chars act like ASCII numbers
    // handle this problem
    return -1; //error
  } else {
    return int(input - '0'); // input's code - '0''s code = number
  }
}

處理用戶輸入時,我將使用以下方法:

string l;
if(!getline(cin, l))
    /* handle error that no input could be read at all */
try
{
    int const res = boost::lexical_cast<int>(l);
    /* numerically validate input here */
    return res;
}
catch(exception const&)
{
    /* handle parsing error here */
}

換句話說,讀取一行,然后使用Boost的lexical_cast()函數模板進行解析和驗證。 請注意,如果有人(例如通過shell重定向)從文件中讀取輸入,則會發生第一個錯誤,即getline()失敗,但這也可以通過某些按鍵操作來實現,具體取決於shell。 此狀態無法恢復,因此提示輸入不同的答案將導致無限循環。

如果您查看>>提取運算符的文檔,例如:

http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

您會注意到以下報價:

(1)算術類型從流中順序提取和解析字符,以將它們解釋為適當類型的值的表示形式,該類型存儲為val的值。

從本質上講,這意味着程序將嘗試將您傳遞的所有數據均以rvalue指定的格式(在您的情況下為int)對待。 更簡單:在您的情況下,它將嘗試對要傳遞到流中的內容進行整數化,並使數據變得“整數”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM