簡體   English   中英

如何在 C++ 中忽略錯誤的 cin 輸入?

[英]How to ignore wrong cin input in C++?

這是 4x4 井字棋游戲的代碼。 我是編程新手。 我不知道如何忽略用戶的錯誤輸入。 我嘗試搜索谷歌,我找到了cin.clear()cin.ignore() 他們確實工作了一點,但沒有完全工作。 例如,如果用戶輸入11111111 4 o作為輸入,程序將退出而不是忽略它。 如何忽略此輸入?

cin.clear()cin.ignore()在做什么?

char game[4][4]; 
int r, c;
char ans;
cin >> r >> c >> ans;
--r, --c;
if (!check_ok(r, c, ans)){
    cout << "try again: select available ones only!!!\n";
    --count;//count checks for 16 turns through while loop

}else{
    game[r][c] = ans;
    ++count1;
}
bool Game::check_ok(int a, int b, char an) {
    if (game[a][b] == ' ' && a < 4 && b < 4  && ((count1 % 2 == 0 && an == 'x') || (count1 % 2 != 0 && an == 'o'))){
        game[a][b] = an;
        return true;
    }
    else{
       cin.clear();
       cin.ignore();
       return false;
    }
}

好的。 用戶輸入很難。

交互式用戶輸入是基於行的。
用戶輸入一些值,然后點擊返回。 這會刷新流並解鎖讀取器以從流中獲取值。 因此,您應該將輸入代碼設計為基於行。

第一個問題似乎是所有輸入都在一行上,還是他們輸入的值在每個值之間都有一個返回值? 您可以通過對用戶的一些輸出來確定這一點,然后按照您的說明定義的規則進行操作。

所以讓我們做一個基於行的輸入示例:

do {
    // Your instructions can be better.
    std::cout << "Input: Row Col Answer <enter>\n";

    // Read the user input. 1 Line of text.
    std::string  line;
    std::getline(std::cin, line);

    // convert user input into a seprate stream
    // See if we can correctly parse it.
    std::stringstream linestream(std::move(line));

    // Notice we check if the read worked.
    // and that the check_ok() returns true.
    // No point in call check_ok() if the read failed.
    if (linestream >> r >> c >> ans && check_ok(r, c, ans)) {
        break;
    }
    std::cout << "Invalid Input. Please try again\n";
}
while(true);

我認為不應忽略錯誤的輸入,而應將用戶輸入限制為僅理想的輸入。 也許 if 語句會有所幫助

if(input != ideal_input)
{
    cout>>"invalid input";
}
else
{
    //progress in the game
}

暫無
暫無

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

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