簡體   English   中英

如何解決cin.fail()中的循環

[英]How to solve the loop in cin.fail()

知道為什么會這樣嗎?

樣品運行

void askNQ(int &noq)
{
    bool x = true;
    while (x)
    {
        int i;
        cout << "How many questions would you like(out of " << noq << ")?" << endl;
        cin >> i;

        if (cin.fail())
        {
        cin.clear();
        cin.ignore();
        cout << "Sorry, that is not valid." << endl;
        x = true;
        }
        else if (i > noq)
        {
            cout << "Sorry, that is too many." << endl;
            x = true;
        }
        else if (i <= 0)
        {
            cout << "Sorry, that is too less." << endl;
            x= true;
        }
    }
}

cin.ignore(); 實際上是對cin.ignore(1, char_traits<char>::eof());的調用cin.ignore(1, char_traits<char>::eof());

因此,您不會從任何剩余的換行符中清除緩沖區。

以下應解決您的問題:

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

無論緩沖區中有多遠,它都會清除下一個換行符(出於所有實際目的)。

您應該在命令行中輸入數字,因為變量“ i”是整數。

暫無
暫無

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

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