2016-07-16 3 views
1

この小さなテストは、私のプログラムの問題点を突き止めるのに役立ちました。今、奇妙なことが起きています。第3の最後のscanf()がスキップされ、直後のテスト行がの値10を出力します。scanf()の後にこのポインタがデフォルト値10になるのはなぜですか?

void takeTurn(int *iap, int *tile, char *cap) { 
    printf("\n\tPRINT TEST Take Turn()\n"); 

    if (*iap == 1) *cap == 'X'; 
    if (*iap == 2) *cap == 'O'; 

    printf("\nWhich tile would you like?"); 
    printf("\n\tTEST the value of cBoard[0] is %c. At [3] is %c.\n1 ::", cBoard[0], cBoard[3]); 
    scanf("%c", &cBoard[0]); 

     //user inputs 'h'. 

    printf("\n\tTEST the value of cBoard[0] is now %c\n2 ::", cBoard[0]); 
    scanf("%d", tile); 

     //it prints 
     //TEST the value of cBoard[0] is now h 
     //user inputs 6. It prints 

    printf("\n\tTEST the value of cBoard[%d] is %d.\n3 ::", *tile, cBoard[*tile]+1); 

     //it prints 
     //TEST the value of cBoard[6] is 1. 

     scanf("%c", &cBoard[*tile]); 

     //This scanf() does not run. 

    printf("\n\tTEST the value of cBoard[%d] is %d.\n", *tile, cBoard[*tile]); 

     //it prints 
     //TEST the value of cBoard[6] is 10. 

    ... 
} 

最終印刷では、以前の割り当てが何であっても、cBoard[6]が10として返されます。不適切な機能についての何かは、新しい値を10に設定する必要があります。

何が起こっていますか?

答えて

4

scanf("%d", tile);は数字を読み取りますが、'\n'は標準入力バッファに残ります。次の読み取り操作scanf("%c", &cBoard[*tile]);はこの文字を読み取ります。この文字はASCIIで値10になります。あなたはと文字の前に空白を無視して行動を修正することができます。

scanf(" %c", &cBoard[*tile]); // notice the space before the %c 

注意また、あなたが正しい入力が提供されたことを確認するためにscanfの戻り値をチェックする必要があること。

+0

ありがとうございました。 – Naltroc

関連する問題