[英]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;
}
任何幫助,將不勝感激。
代碼中的一些問題:
cin
( if
在if
條件中一次, 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.