我目前正在嘗試學習C,並決定做一個簡單的井字遊戲「遊戲」。簡單的C井字遊戲輸入錯誤
我不想做任何奇特的事情,我只想把用戶的位置和他們給定的角色放在我的網格中。我還沒有開始使用數組或任何東西,所以我使用printf組合了一個網格。
問題出現在我試圖實際運行遊戲時,角色不起作用。我可以輸入正確的輸入,但它只是使該位置變爲空白。我如何使這個switch語句存儲我想要的字符?
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Initialize and define all variables and characters
char c1='.', c2='.', c3='.', c4='.', c5='.', c6='.', c7='.', c8='.', c9='.'; // Board characters
char given; // User-input character
int pos; // User-input position for the character
int turnCount; // Gives a limit on game length
for (turnCount = 0; turnCount < 9; turnCount++)
{
// Display lines
printf("%c %c %c 1 2 3\n", c1, c2, c3); // First line
printf("%c %c %c 4 5 6\n", c4, c5, c6); // Second line
printf("%c %c %c 7 8 9\n", c7, c8, c9); // Third line
// Asks for input, scans input for position and character to use
printf("Choose a position and character, without spaces.\n");
scanf_s("%i%c", &pos, &given);
// Matches the input position with a character, defines the character
switch (pos)
{
case 1: c1 = given; break;
case 2: c2 = given; break;
case 3: c3 = given; break;
case 4: c4 = given; break;
case 5: c5 = given; break;
case 6: c6 = given; break;
case 7: c7 = given; break;
case 8: c8 = given; break;
case 9: c9 = given; break;
} // End switch
} // End for - game should be over
return 0;
}
總是很好地檢查'scanf_s()'的結果。 – chux