簡體   English   中英

如何創建一個循環,讓用戶在 cin.fail() 發生時重新輸入他們的答案?

[英]How do I create a loop that lets the user re-enter their answer when a cin.fail() occurs?

我的程序的這一小段似乎引起了一些問題:

cout << "Would you like to change the values? Type 1 if yes or 2 if no." << endl << "You can also reverse the original vector above by typing 3. \n Answer:  ";
    cin >> yesorno;

    while (yesorno != 1 && yesorno != 2 && yesorno != 3 || cin.fail() )
        {           
        cout << "\n Sorry, didn't catch that. Try again: ";
        cin >> yesorno;
        }

據我所知,該循環適用於所有有效整數,但是當無效值被聲明為yesorno ,循環會崩潰。 例如,如果我輸入字母 A,則循環無限循環。 我想我要問的是,如何才能讓用戶有無限的機會輸入有效值? 順便說一句,我對 C++ 還很陌生,所以我不熟悉所有不同類型的公共成員函數等。我試過 cin.clear() 但沒有取得多大成功

當您在讀取輸入數據時遇到錯誤,您可以使用cin.clear()清除流的狀態,然后調用cin.ignore()以忽略該行的其余部分。

while ( (yesorno != 1 && yesorno != 2 && yesorno != 3) || cin.fail() )
{           
   cout << "\n Sorry, didn't catch that. Try again: ";
   if ( cin.fail() )
   {
      cin.clear();
      cin.input.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

   cin >> yesorno;
}

我更喜歡的另一種方法是逐行讀取輸入並獨立處理每一行。

std::string line;
while ( getline(cin, line) )
{
   std::istringstr str(line);
   if ( !(str >> yesorno) || (yesorno != 1 && yesorno != 2 && yesorno != 3) )
   {
      cout << "\n Sorry, didn't catch that. Try again: ";
      continue;
   }
   else
   {
      // Got good input. Break out of the loop.
      break;
   }
}

fail位被設置時,您需要在繼續之前清除它。

while (yesorno != 1 && yesorno != 2 && yesorno != 3 || cin.fail() )
{           
        if ( cin.fail() ) {
                cin.clear();
                cin.ignore( std::numeric_limits<std::streamsize>::max() );
        }
        cout << "\n Sorry, didn't catch that. Try again: ";
        cin >> yesorno;
}

暫無
暫無

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

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