簡體   English   中英

為什么std :: cin同時接受多個輸入?

[英]Why does std::cin accept multiple inputs at the same time?

我為基於文本的游戲編寫了一個代碼,該代碼在每個回合開始時都會接受用戶輸入,並且應該根據輸入內容執行不同的操作。 例如,“向上”應將玩家在網格上向上移動1個空間,“外觀”應顯示該空間的指定風景。 任何未指定為有效輸入的內容都會導致系統輸出錯誤消息,“我聽不懂”。 問題是:如果我鍵入類似“向上,向下,向右看”的命令,它將按順序執行每個命令,而不顯示錯誤消息。

 string input = "";
while(input!="quit")
{ 
    cin >> input;
    if (input == "left") {
        if (map[player1.y][player1.x - 1].isWall==true)
            cout << map[player1.y][player1.x - 1].scene;
        else if (player1.x > 0)
            player1.x -= 1;
        else
            cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
    }
    else if (input == "right") {
        if (map[player1.y][player1.x + 1].isWall==true)
            cout << map[player1.y][player1.x + 1].scene << endl;
        else if (player1.x < cols-1)
            player1.x += 1;
        else
            cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
    }
    else if (input == "up") {
        if (map[player1.y - 1][player1.x].isWall==true)
            cout << map[player1.y - 1][player1.x].scene;
        else if (player1.y > 0)
            player1.y -= 1;
        else
            cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
    }
    else if (input == "down") {
        if (map[player1.y + 1][player1.x].isWall==true)
            cout << map[player1.y + 1][player1.x].scene;
        else if (player1.y < rows-1)
            player1.y += 1;
        else
            cout << "You walked off the face of the Earth, but grabbed the ledge just before it was too late. \n Somehow, you managed to gather enough strength to pull yourself back up. \n ...Maybe don't try that again." << endl;
    }
    else if (input == "look")
        map[player1.y][player1.x].look();
    else if (input == "take")
        player1.pickupCons(map[player1.y][player1.x].potions[0]);
    else
    {
        cout << "I don't understand... type something else!" << endl;
        continue;
    }

您正在使用“格式化”輸入運算符>> 基本上,格式化的輸入操作在看到空白字符時將停止並返回。 因此,使用輸入“向上看,向下看,向右看”,您的while循環實際上對輸入中的每個命令執行了六次。

如果一行中沒有多個命令,請改用std::getline

while(getline(cin, input)) {
    if (input == "quit") break;
    if (input == "up") ...
}

暫無
暫無

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

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