2011-11-17 34 views
1

我的代碼如下,爲什麼scanf()函數不會從用戶那裏獲得輸入?

typedef struct 
{ 
char name[15]; 
char country[10]; 
}place_t; 

int main() 
{ 
int d; 
char c; 
place_t place; 
printf("\nEnter the place name : "); 
scanf("%s",place.name); 
printf("\nEnter the coutry name : "); 
scanf("%s",place.country); 
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?"); 
scanf("%c",&c); 
printf("You entered %c",c); 
return 0; 
} 

如果我運行程序,它會提示地名和國家名稱。但它永遠不會等待用戶輸入的字符,只是在輸出屏幕上輸出空白值。我試過

fflush(stdin); 
fflush(stdout); 

兩者都不會工作。

注意:如果我編寫代碼來獲取整數或浮點數,它會提示輸入值,而不是字符。

printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?"); 
scanf("%d",&d); 

這是爲什麼發生?代碼是否有問題或者scanf是否自動從緩衝區獲取值?如何解決這個問題?

回答

2

問題是,scanf在流緩衝區中輸入非空白字符後留下空白,這是scanf(%c...)然後讀取的內容。但等一下...

除了棘手得到正確的,這樣的代碼使用scanf是非常不安全的。你已經開使用fgets後來解析字符串好得多:

char buf[256]; 
fgets(buf, sizeof buf, stdin); 
// .. now parse buf 

fgets總是能夠從輸入一個完整的系列,包括換行符(假設緩衝區足夠大),因此你避免你的問題」重新與scanf

1

您可以使用字符串代替scanf的字符。

1
printf("\nEnter the place name : "); 
scanf("%s%*c",place.name); 
printf("\nEnter the coutry name : "); 
scanf("%s%*c",place.country); 
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?"); 
scanf("%c",&c); 
printf("You entered %c",c); 
相關問題