2012-02-25 144 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