【问题标题】:C: function skips user input in codeC:函数在代码中跳过用户输入
【发布时间】:2012-03-15 12:54:23
【问题描述】:

我遇到了这个功能(战舰游戏的一部分)的问题,它会完美地运行一次,但在随后的执行中,它会跳过:

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

}

【问题讨论】:

标签: c loops char printf scanf


【解决方案1】:

你的程序会打印这个提示:

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

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

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

scanf(" %c", &c);

【讨论】:

  • 很好——没想到。
  • 一如既往 - 使用 fgets() 读取一行输入,然后使用 sscanf() 解析它。或者至少循环使用getchar() 以在每个字符之后读取换行符,或者......沿着这些一般线路。
【解决方案2】:

当用户按下回车键时,这也是一个将在输入缓冲区中的字符。您需要阅读过去的内容。

//prints grid so player can check it for their next move
Print_Play_Grid(PlayGrid);
while (fgetc(stdin)!='\n') { }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2021-11-29
    • 2016-04-26
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多