看板 C_and_CPP 關於我們 聯絡資訊
自己碰到了才有感覺, scanf 比想像中還難。 後來找到 __fpurge(stdin) 終於清掉 stdin buffer。 __fpurge 是 linux 提供的。 linux man page 提到: For input streams associated with seekable files (e.g., disk files, but not pipes or terminals), 也許 stdin 不算是 seekable files 吧! 所以 fflush(stdin) 無效。 另外「C程式語言」B-4 提到 fflush 對於 input streams, 結果未定義 (undefined behavior)。出自 K&R, 相信夠份量。 另外一個有可攜性的作法就是把 stdin buffer 讀出來丟掉。 int c; while ((c = getchar()) != '\n' && c != EOF); https://descent-incoming.blogspot.com/2022/03/c-scanf.html 一些 scanf 的心得。 ※ 引述《wtchen (沒有存在感的人)》之銘言: : 使用Lubuntu + gcc 4.9.2 : 問題(Question): : 目前在練習file input/output : 有個疑問是如何不要讓前面輸入的Enter影響到後面 : 看了一下自己手上的書「邊學邊做C語言」是用fflush(stdin) : 不過我加進去以後根本沒反應,輸入完要求的char+Enter程式就直接跑到底 : 然後看了版友的建議用while(getchar()!='\n'); : (不過我不太懂,這邊最後一個getchar()不是輸入完要求的char打的'\n'嗎?) : 可是的確有用,程式的確停下來叫我輸入string : 稍微看了一下好像有些大大說不能用fflush(stdin) : 可是google一下發現很多人都在用 : 我自己對fflush的認識也是把之前輸入到buffer裡的清掉 : 還是我對fflush的認識有誤? : 感謝各位協助。 : 程式同步分享在此: : https://gist.github.com/gnitnaw/ac3dbcd8fa8e11c515c8 : #include <stdio.h> : #define MAXSIZE 256 : void read_string(char* p); //可以用scanf或fgets替代,我兩個都不滿意所以自己寫 : int main(void) { : char c, s[MAXSIZE]; : puts("I/O lib"); : puts(""); : printf("Please give me a char: "); : c = getchar(); : printf("What you keyin is %c\n", c); : fflush(stdin); : while(getchar()!='\n'); : printf("Please give me a string : "); : read_string(s); : printf("What you keyin is %s\n", s); : printf("\n Press <Enter> to continue..."); : while ((c=getchar()) != '\n'); : return 0; : } : void read_string(char* p) { : int i; : char c; : for (i=0; i<MAXSIZE-1; ++i) { : if ( (c=getchar()) != '\n' ) { : p[i] = c; : } else { : break; : } : } : p[i] = '\0'; : } -- 紙上得來終覺淺,絕知此事要躬行。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.217.135.250 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1647604378.A.411.html
Schottky: 把 buffer 讀出來丟光 +1 03/18 20:41
wei115: 緩衝區有夠難搞的= = 讀出來丟掉真的是最可靠的 另外用 03/18 22:45
wei115: %*[^\n]%*c比較炫泡 03/18 22:45
wei115: 當初刷uva被緩衝區衝康很多次 03/18 22:46