2010-09-16 36 views
3

當我運行下面的代碼片段時,它會運行到第二個問題。然後它將「客戶是學生嗎?(y/n)\ n」和「什麼是電影時間?(以小時爲單位)\ n」一起提示(沒有區域來回答他們之間的問題)。如果從那裏採取任何行動,程序將停止工作。我做錯了什麼? (我敢肯定它的語法關係)使用C scanf語法的幫助

int A,B,C,D,age,time; 
char edu, ddd; 

printf ("What is the customer's age? \n"); 
scanf("%d", &age); 

printf ("Is the customer a student? (y/n) \n"); 
scanf("%c", &edu); 

printf ("What is the movies time? (in hours) \n"); 
scanf("%d", &time); 

printf ("Is the movie 3-D? (y/n) \n"); 
scanf("%c", &ddd); 
+2

[This](http://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c)可能會有所幫助。 – sje397 2010-09-16 04:45:29

+1

最好避免使用'scanf':http://c-faq.com/stdio/scanfprobs.html – jamesdlin 2010-09-16 05:52:44

回答

4

你可能需要在每次scanf函數後吃從標準輸入額外的輸入,所以它不會在緩衝區堅持圍繞並導致scanf函數接收緩存數據。

這是因爲在第一個文本輸入後輸入的換行符保留在緩衝區中並且是「%c」格式的有效輸入 - 如果查看「edu」的值,您應該發現它是換行符字符。

2

您可以在%c之前添加空格。這是必要的,因爲不像其他轉換說明符,它不會跳過空格。因此,當用戶輸入類似「10 \ n」的年齡時,第一個scanf可以讀取到10的結尾。然後,%c讀取換行符。該空間告訴scanf在讀取字符之前跳過所有當前空白。

printf ("What is the customer's age? \n"); 
scanf("%d", &age); 

printf ("Is the customer a student? (y/n) \n"); 
scanf(" %c", &edu); 

printf ("What is the movies time? (in hours) \n"); 
scanf("%d", &time); 

printf ("Is the movie 3-D? (y/n) \n"); 
scanf(" %c", &ddd); 
4

當讀取使用scanf輸入,按下後返回鍵,而是由返回鍵生成的新行不被scanf,這意味着未來你從標準輸入讀取會有時間消耗的輸入被讀取準備閱讀的換行符。

避免的一種方法是使用fgets將輸入讀取爲字符串,然後使用sscanf提取您想要的內容。

消耗換行符的另一種方法是scanf("%c%*c",&edu);%*c將從緩衝區讀取換行符並丟棄它。

2

scanf和「%c」有任何問題,請參閱:@jamesdlin。 「時間」是一個C-標準 - 庫函數的名稱,更好地使用不同的名稱,如:

int A,B,C,D,age=0,timevar=0; 
char edu=0, ddd=0, line[40]; 

printf ("What is the customer's age? \n"); 
if(fgets(line,40,stdin) && 1!=sscanf(line,"%d", &age)) age=0; 

printf ("Is the customer a student? (y/n) \n"); 
if(fgets(line,40,stdin) && 1!=sscanf(line,"%c", &edu)) edu=0; 

printf ("What is the movies time? (in hours) \n"); 
if(fgets(line,40,stdin) && 1!=sscanf(line,"%d", &timevar)) timevar=0; 

printf ("Is the movie 3-D? (y/n) \n"); 
if(fgets(line,40,stdin) && 1!=sscanf(line,"%c", &ddd)) ddd=0; 

在結束你的增值經銷商有一個定義的內容,0爲輸入錯誤,!否則爲0。

1

使用fflush(stdin);

聲明明確標準輸入的緩衝存儲器中讀取任何字符數據

之前,否則它會讀取到第二scanf函數的輸入第一個scanf函數的鍵值。

0

我想你的計劃,似乎打字歲以後,當我按下回車鍵,認爲作爲輸入下一個scanf函數(即用於& EDU)同樣地,對於第三和第四個問題。我的解決方案可能很幼稚,但你可以簡單地在每一個緩衝區之後使用緩衝區scanf來吸收「Enter」。或乾脆這樣做

scanf(" %c", &variable); 

(格式字符串中的任何空格將使scanf吸收所有更多的連續空格)。