0

我是 C 编程的新手,我有这个任务需要我创建一个简单的井字游戏。

我设法用数组和循环创建了一个空板。现在我需要获取用户的输入,并将“X”/“O”放入板中。

这是代码:

 #include <stdio.h>
#include <stdlib.h>

int main()
{    
    //Declare the variables
    //Create the board
        //Initialize the board with all blanks
        //Print to screen
    //Prompt user for letter 'X', 'O' or 'q' to quit

    //declare the variables
    char board[3][4], input;
    int rows, columns;

do
    {
        //create the board
        for ( rows = 0 ; rows <3 ; rows++ )
        {
            for ( columns = 0 ; columns < 4 ; columns++ )
            {
                //Initialize array to blanks (' ')
                board[rows][columns] = '|';

                //print to screen
                printf( "%c\t", board[rows][columns] );
            }
            printf("\n\n\n");
        }

        printf( "Hit X or O. 'q' to quit\n\n" );
        scanf("%c", &input);

    } while ( input != 'q' );
}//end main

任务说我可以使用这段代码fflush(stdin)来清除键盘缓冲区,我显然不知道它是什么以及如何使用它:(

我对该代码进行了一些研究,它似乎取代了现有的输入和输出。如果我错了,请纠正我。

fflush(stdin)那么在我目前的情况下如何使用?

山姆

4

1 回答 1

0

当您在这些调用之间使用 scanf 两次而没有 fflush 时,您可能会在第二次调用时得到错误/无输入,例如因为第一个输入的输入仍在缓冲区中。在这种情况下,scanf 将返回一个空字符串。

为了绝对安全,您可以在每次扫描后刷新标准输入。

于 2013-10-22T12:15:44.907 回答