std::cin 錯誤之後的重置

std::cin 錯誤之後的重置

範例程式

while(1)
{
    cin>>變數;
    if(cin.good())
        break;
    cin.clear();
    cin.seekg(0,ios::end);
    cout<<"輸入錯誤 請重新輸入";
}

分析

cin提供了good()跟fail()兩個member function來判斷stream的正確性,只是在判斷正確性之後要讓他回覆到工作狀態要將current position歸位。因此加上seekg函式來輔助。
此方式也可以改寫成

while(1)
{
    cin>>變數;
    if(cin.fail())
    {
        cin.clear();
        cin.seekg(0,ios::end);
        cout<<"輸入錯誤 請重新輸入";
    }
}

當然此偵測只能針對變數為整數或浮點數,卻輸入英文或符號的這類例子。
其他種類的容錯可以使用string去接cin之後在自己來處理。
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-NoDerivs 3.0 License