2015-11-01 46 views
3

基本上我是一個初學者編碼器和這是我寫的:C代碼死機(不知道爲什麼)

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
system("COLOR 0A"); 

char playerName[13]; 
char playerGender; 
int playerAge; 

printf("Please input your name and age!\nName: "); 
scanf("%s", playerName); 
printf("Age (from 18 to 50): "); 
scanf("%d", &playerAge); 

label: 
if(playerAge > 18 && playerAge < 50) 
{ 

    printf("What gender are you, M(male) or F(female): "); 
    scanf("%c", playerGender); 

    gender: 
    if(playerGender == 'M' || playerGender == 'F'){ 

     printf("Okay, so your name is %s, you're %d years old and you're a %s.", playerName, playerAge, playerGender); 
    }else{ 
     printf("Try again.\n\n" 
      "What gender are you, M(male) or F(female): "); 
      scanf("%c", playerGender); 
      goto gender; 
    } 
}else{ 

     printf("Wrong, try again.\n" 
       "Age (from 18 to 50): "); 
     scanf("%d", &playerAge); 
     goto label; 
} 


return 0; 
} 

當我把所要求的年齡繼續,它崩潰的scanfplayerGender。之後它向我展示了關於我的性別的問題?我的錯誤在哪裏?

+0

主要問題是使用'scanf'進行用戶輸入。 – melpomene

+3

儘管你是初學者,但你應該有常識來包含你的完整程序和對其行爲的描述。這是非常好的! –

+0

從一開始就學會不使用goto。 – Unimportant

回答

10

嘗試:的

scanf("%c", &playerGender); 

代替

scanf("%c", playerGender); 

爲scanf函數需要一個指針,而不是你正試圖填補變量的引用。

0

我也是新手,但我認爲你需要寫這個scanf("%s", playerName);這樣scanf("%12s", playerName);

順便說一句讓我知道是否可行。

+0

這隻會明確地告訴'scanf'要使用的字符串由12個字符組成。它防止緩衝區溢出,以防用戶輸入超出要存儲的數組的長度,並且它的長度爲12個字節。 – Malina

相關問題