簡體   English   中英

如何在 C++ 中正確使用 cin.fail()

[英]How to use cin.fail() in c++ properly

我正在編寫一個程序,通過cin>>iUserSel;從用戶那里獲得一個整數輸入cin>>iUserSel; . 如果用戶輸入一個字母,程序就會進入無限循環。 我試圖用下面的代碼防止這種情況發生,但程序進入無限循環並打印出“錯誤!輸入#!”。 如何修復我的程序?

cin>>iUserSel;
while (iValid == 1)
{
        if (cin.fail())
        {
                cin.ignore();
                cout<<"Wrong! Enter a #!"<<endl;
                cin>>iUserSel;
        }//closes if
        else
                iValid = 0;
}//closes while

我在使用 cin.fail()C++ cin.fail() 問題的正確方法中找到了一些關於此的信息,但我不明白如何使用它們來解決我的問題。

cin失敗時,需要清除錯誤標志。 否則后續的輸入操作將是非操作。

要清除錯誤標志,您需要調用cin.clear()

您的代碼將變為:

cin >> iUserSel;
while (iValid == 1)
{
    if (cin.fail())
    {
        cin.clear(); // clears error flags
        cin.ignore();
        cout << "Wrong! Enter a #!" << endl;
        cin >> iUserSel;
    }//closes if
    else
        iValid = 0;
}//closes while

我也建議你改變

cin.ignore(); 

cin.ignore(numeric_limits<streamsize>::max(), '\n'); 

如果用戶輸入多個字母。

您遇到的問題是您沒有從流中清除failbit 這是通過clear函數完成的。


在有些相關的說明中,您根本不需要使用fail函數,而是依賴於輸入運算符函數返回流的事實,並且該流可以在布爾條件中使用,然后您可以執行類似的操作以下(未經測試)代碼:

while (!(std::cin >> iUserSel))
{
    // Clear errors (like the failbit flag)
    std::cin.clear();

    // Throw away the rest of the line
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Wrong input, please enter a number: ";
}

以下是我的建議:

// Read the data and check whether read was successful.
// If read was successful, break out of the loop.
// Otherwise, enter the loop.
while ( !(cin >> iUserSel) )
{
   // If we have reached EOF, break of the loop or exit.
   if ( cin.eof() )
   {
      // exit(0); ????
      break;
   }

   // Clear the error state of the stream.
   cin.clear();

   // Ignore rest of the line.
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   // Ask more fresh input.
   cout << "Wrong! Enter a #!" << endl;
}

暫無
暫無

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

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