簡體   English   中英

在C ++中驗證二進制輸入

[英]Validating binary input in C++

嗨,我正在嘗試驗證用戶輸入,以查找1或0的輸入。字符串驗證部分似乎工作正常,但是任何基於整數的輸入都具有控制台窗口接受輸入但不跳過if語句,返回輸入(maxItems)。 這是代碼:

int RollingStats::GetOption() 
{
       int maxItems;

        std::cout << "Please enter either to store data individually (0) or as a range(1)" << std::endl;

        std::cin >> maxItems;

        if ((!(std::cin >> maxItems) && maxItems != 0) | (!(std::cin >> maxItems) && maxItems != 1))
        {
            std::cin.clear();

            std::cin.ignore(100, '\n');

            std::cout << "Please enter an input of either 0 or 1" << std::endl;

            GetOption();
        }
            return maxItems;
} 

任何幫助,將不勝感激。

代碼中的一些問題:

  • 三次使用cinifif條件中一次, if和兩次),則需要用戶輸入三次
  • if條件檢查中,使用邏輯OR( || )代替按位或( | )。
  • 不檢查輸入是否為整數

您可以改為執行以下操作:

int RollingStats::GetOption()
{
    int maxItems;
    std::cout << "Please enter either to store data individually (0) or as a range(1)" << std::endl;
    std::cin >> maxItems;

    if(!std::cin.good() || maxItems != 0 && maxItems != 1)
    {
        std::cin.clear();
        std::cin.ignore(100, '\n');
        std::cout << "Please enter an input of either 0 or 1" << std::endl;
        maxItems = GetOption();
    } 
    return maxItems;
}

暫無
暫無

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

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