为什么std::cin同时接受多个输入

  • 本文关键字:std cin c++ user-input cin
  • 更新时间 :
  • 英文 :


我为一个基于文本的游戏编写了一段代码,该游戏在每回合开始时接受用户输入,并根据输入做不同的事情。例如,"向上"应将玩家在网格上向上移动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") ...
}

相关内容

  • 没有找到相关文章

最新更新