CTRL + Z使程序在C ++中无限循环

时间:2013-03-22 20:24:00

标签: c++ loops

好的我在这里遇到了问题。我正在制作一个幻灯片益智游戏。向玩家询问他想要移动哪件作品直到拼图解决。如果玩家想要之前退出,请键入Qq并按enter即可。该程序工作得很好。但是我遇到了一个问题:如果我插入CTRL+Z,该程序会loop意外地... {/ p>

这是重要的代码:

        // 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.";
            }
        }

1 个答案:

答案 0 :(得分:5)

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;
}