1

好的,我这里有问题。我正在制作一个幻灯片益智游戏。玩家被问到他想要移动哪一块,直到谜题被解决。如果玩家之前想退出,输入Qq按即可enter。该程序运行良好。但是我有一个问题:如果我插入CTRL+Z,程序会loop出乎意料地......

这是一段重要的代码:

        // analyzes user input
        if (piece_to_move_string == "q" ||
            piece_to_move_string == "Q")
        {
            cout << endl << "You chose to quit." << endl;
            pressanykey();
            break;
        }
        else
        {
            piece_to_move = atoi(piece_to_move_string.c_str());

            if (1 <= piece_to_move && piece_to_move <= pow(puzzle_size,puzzle_size))
            {
                game_board = move_piece (game_board, piece_to_move);
            }
            else
            {
                cout << "Not possible.";
            }
        }

编辑:但仍然不起作用..

// analyzes user input
        if (piece_to_move_string == "q" ||
            piece_to_move_string == "Q")
        {
            cout << endl << "You chose to quit." << endl;
            pressanykey();
            break;
        }
        else if (cin.eof())
        {
            //do nothing
        }
        else
        {
            piece_to_move = atoi(piece_to_move_string.c_str());

            if (1 <= piece_to_move && piece_to_move <= pow(puzzle_size,puzzle_size))
            {
                game_board = move_piece (game_board, piece_to_move);
            }
            else
            {
                cout << "Not possible.";
            }
        }
4

1 回答 1

6

Ctrl+Z表示“文件结尾”(假设您在 Windows 上),因此一旦用户点击它,您cin就处于不可读状态。检查cin.eof()

if (cin.eof() || piece_to_move_string == "q" ||
                 piece_to_move_string == "Q")
{
    cout << endl << "You chose to quit." << endl;
}
于 2013-03-22T20:25:56.987 回答