2016-04-21 224 views
1

如何讓玩家能夠輸入一個座標(x,y)(1,2),同時還能夠選擇輸入字符如'c'或's'?我該如何使用scanf輸入座標,如果需要在此功能中還需要一個字符

我可以將x改爲char,然後使用%c作爲第一個輸入,然後讓if(x =='1')x = 1等等,但它仍然會給我分段錯誤,因爲它需要掃描y的東西。我怎樣才能解決這個問題?

matrix[][]是一個全局char二維數組。

void updateTablePlayer1(void) 
{ 

    int y, x; 


    printf ("Enter a command for player 1 ([row,col], c, s, p):"); 
    scanf ("%d,%d", &x, &y); 

    x--; 
    y--; 

    if (matrix[x][y]!= ' ') 
    { 
     printf ("Invalid selection\n"); 
     updateTablePlayer1(); 
    { 

    else if (x == 'c') 
    { 
     createClearTable(); 
     displayTable(); 
     updateTablePlayer1(); 
    } 

    else if (x == 's') 
    { 
     displayTable(); 
     updateTablePlayer1(); 
    } 

    else if (x == 'p') 
    { 
     displayTableImage(); 
     updateTablePlayer1(); 
    } 

    else 
     matrix[x][y] = 'X'; 


    } 
+0

使用'scanf'的返回值。 – Dan

回答

1

您的scanf調用有兩件事:讀取某些輸入並將其解釋爲數字。分開這兩件事:讀一個字符串,然後解釋它。

使用fgets而不是scanf來讀取字符串可能更好。當您的輸入看起來像包含數字時,您可以使用sscanf對它們進行解碼。

2

有一個地方叫scanf()-這是一個邪惡的地方,被鯊魚包圍並且爬滿了蛇。折磨的悲傷代碼屍體散佈着。

有一個更快樂的地方叫做fgets()-地。它有一些顛簸和陷阱,但更安全 - 帶有很長的舊灰色鬍鬚的代碼居住在那裏。


步驟1:刷新輸出,以保證緩衝並不妨礙它被示出輸入

printf ("Enter a command for player 1 ([row,col], c, s, p):"); 
fflush(stdout); 

步驟2:讀取線

// scanf ("%d,%d", &x, &y); 
char buffer[80]; 
if (fgets(buffer, sizeof buffer, stdin) == NULL) Handle_input_closed(); 

步驟3:解析輸入。總是檢查錯誤。

int x,y; 
char command; 
if (sscanf(buffer, "%d,%d", &x, &y) == 2) { 
    Do_xy_Stuff(); 
} 

else if (sscanf(buffer, " %c", &command) == 1) { 
    if (command == 'c') Do_c_Stuff(); 
    else if (command == 's') Do_s_Stuff(); 
    else if (command == 'p') Do_p_Stuff(); 
    else Complain_about_bad_input(); 

} else { 
    Complain_about_bad_input(); 

} 
相關問題