我对此功能(战舰游戏的一部分)有问题,该功能可以很好地通过它运行,但是在随后的执行中,它会跳过:

    scanf("%c",&rChar);


由于某些原因,rChar会变成另一个值,而无需用户从上述代码中输入。
我尝试在整个函数中放入printf语句来显示rChar的值。

函数Conv_rChar_Int()将用户输入的Char转换为整数值。但是因为rChar不会作为指针传递,所以rChar的值始终保持不变,直到用户在下一次迭代中将其替换为止。 (使用printf再次验证)。奇怪的是,它在这些代码行之间进行了更改。并且从不提示用户输入rChar

    printf("please enter the row you want to place your %d ship in\n",length);
    scanf("%c",&rChar);


请记住,它只会在第一次之后发生。即使每次迭代后重新初始化变量rCharrcdir,此问题仍然会发生。
我99%确信问题出在此函数内,而不是在其中调用的任何函数内(因为rChar在每一行之后都保持不变,除了上述两行之间)。

预先感谢您的帮助。如果您对代码有任何疑问,我将尝试进一步说明。

int Gen_Ship_Place(int length, int flag3, int PlayGrid[10][10]){
int ShipPlaceFlag = 0;

//coordinates and direction
int r;
char rChar;
int c;
int dir;

//this loops until a ship location is found
while(ShipPlaceFlag == 0)
{
    //enters row
    printf("please enter the row you want to place your %d ship in\n",length);
    scanf("%c",&rChar);

    r = Conv_rChar_Int(rChar);

    //adjusts row
    r--;
    //enter column
    printf("please enter the column you want to place your %d ship in\n",length);
    scanf("%d",&c);

    //adjust column
    c--;

    //enter direction
    printf("please enter the direction you want your %d ship to go\nwith\n0 being north\n1 being east\n2 being south\n3 being west\n",length);

    scanf("%d",&dir);

    //checks ship placement
    ShipPlaceFlag = Check_Ship_Place(length,dir,flag3,r,c,PlayGrid);

    //tells player if the location is wrong or not
    if(ShipPlaceFlag == 0)
    {
        printf("****the location and direction you have chosen is invalid please choose different coordinates, here is your current board*****\n\n");
    }
    else
    {
        printf("****great job, here is your current board*****\n\n");
    }

    //prints grid so player can check it for their next move
    Print_Play_Grid(PlayGrid);

}

最佳答案

您的程序将显示以下提示:

please enter the row you want to place your 2 ship in


并调用scanf。您键入5,然后按回车键。您输入了两个字符:5和换行符\n。 (或者在Windows上可能是\r。)换行符位于输入缓冲区中,直到下一次对scanf的调用为止,该调用将读取换行符并立即返回,而无需输入更多输入。

在读取单个字符时,可以通过在scanf说明符之前放置一个空格,使%c跳过换行符(和其他空格),如下所示:

scanf(" %c", &c);

10-07 15:04