2017-04-15 83 views
0

在簡單程序中學習C時,經常會發生計算機跳過一些代碼行的執行情況,我不明白爲什麼會這樣。在C中跳過代碼行I/O

現在,作爲一個例子,我勾勒它只是存儲3個數字由用戶輸入的程序:

#include <stdio.h> 

int main(void) 
{ 
int a, b, c; 

printf("Please type in number a: \n"); 
scanf("%i", &a); 
printf("Please type in number c: \n"); 
scanf("%i", &c); 
printf("Please type in number b: \n"); 
scanf("%i", &b);  
return 0; 
} 

我想進入1,2和3。這是我在控制檯得到(在Ubuntu中):

Please type in number a: 
1 
Please type in number b: 
Please type in number c: 
2 

編號b的輸入被忽略。

不僅第二個輸入被跳過,所以即使輸入的順序也是錯誤的。最初,我在代碼中按字母順序編寫了所有內容 - a,b和c,然後跳過b的輸入,然後我改變了代碼中的順序,仍然如您所見,執行保持不變。

這種情況我以前有過。

這是怎麼發生的?

+0

按Enter鍵後,字符寫入標準輸入嘗試使用%d而不是%我 – Meccano

+0

。 – ForceBru

+0

@Meccano不起作用 –

回答

0

在第二個想法,我覺得OP還有另一個問題

低於離開社區維基作爲參考


爲了確保scanf()發生前輸出,刷新輸出。

printf("Please type in number a: \n"); 
fflush(stdout); 
scanf("%i", &a); 

printf("Please type in number c: \n"); 
fflush(stdout); 
scanf("%i", &c); 

What are the rules of automatic flushing stdout buffer in C?

+1

我試過'fflush',結果仍然與我在問題中所描述的相同。 –