[英]Accepting only numbers in the user input c++
現在,我正在使用此功能來獲取用戶輸入。
int getOnlyNumber(int num)
{
while (!(cin >> num)) {
// Reset the input:
cin.clear();
// Get rid of the bad input before return was pressed:
while (cin.get() != '\n')
{
continue;
}
// Ask user to try again:
cout << "Please enter a number: ";
}
return num;
}
如果首先輸入字母,這似乎只會捕獲錯誤的輸入。 如果首先輸入一個數字,程序將接受它。 例如 它會接受1e但會捕獲e1。 這是這樣使用的:
displayChoice = getOnlyNumber(displayChoice);
其中displayChoice是一個int。 我需要更改什么以捕獲1e作為輸入或以數字開頭但具有字符串的任何其他輸入?
如果給它一個部分數字,則默認情況下,它將盡力而為,並為您提供它確實能夠理解的位。
如果要查看轉換期間是否有錯誤,則必須檢查cin.fail()。
while (!(cin >> num) || cin.get()!='\n') {
...
您可以使用std::all_of
來測試整個字符串是否為數字:
std::string str;
auto is_digit_check = [] (unsigned char c) { return std::isdigit(c); };
while (!(std::cin >> str) ||
!std::all_of(str.begin(), str.end(), is_digit_check))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return std::stoi(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.