C:函数跳过代码中的用户输入

标签 c loops char printf scanf

我在使用此函数(战舰游戏的一部分)时遇到问题,它会完美地运行一次,但在后续执行中,它会跳过:

    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,它会读取换行符并立即返回,而无需您进行操作需要输入更多内容。

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

scanf(" %c", &c);

关于C:函数跳过代码中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9652924/

相关文章:

c - 函数指针处理程序

loops - loop{} 运行了两次?

mysql - 使用 CHAR(6) 表示年+月字段是个坏主意吗?

c - 关于 C 中的指针和 strcpy()

javascript - 如何在倒数第二条记录处停止JS循环? (xml数据)

c++ - 我如何简单地比较 C++ 中的字符?

c - 从多个循环输入打印输出

c - 为什么我在哈希表中得到相同的值?

c - C中结构体的动态内存分配

linux - 使用 bash 脚本下载和提取解压文件的自动化脚本