2012-02-25 95 views
1

我有一个问题,此功能(战舰游戏的一部分),在其中将通过它运行一次完全正常,但在后续执行,它将跳过用户输入:C:功能跳过代码

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

请记住,它只发生在第一次。即使我在每次迭代之后重新初始化变量rCharr,cdir,仍会发生此问题。 我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); 

} 
+0

http://www.gidnetwork.com/b -60.html – 2012-02-25 05:22:42

+1

http://c-faq.com/stdio/scanfc.html ...为了爱上帝,请停止使用'scanf'。 – jamesdlin 2012-02-25 05:29:35

回答

1

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

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

你的程序打印这样的提示:

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

,并呼吁scanf。您输入5并按返回。您已输入两个个字符:5和换行符\n。 (或者它可能是Windows上的\r)。换行符位于输入缓冲区中,直至下一次调用scanf,它将读取换行符并立即返回而不需要输入更多输入。

您可以scanf通过把一个空间%c说明符之前,这样的读取一个字符时跳过换行符(和其他空白):

scanf(" %c", &c); 
+0

不错 - 没有想到这一点。 – 2012-02-25 05:32:53

+0

一如既往 - 使用'fgets()'读取一行输入,然后'sscanf()'来解析它。或者至少用'getchar()'循环来读取每个字符后面的换行符,或者......沿着这些通用行来读取。 – 2012-02-25 06:38:42