作者descent (「雄辩是银,沉默是金」)
看板C_and_CPP
标题Re: [问题] 关於fflush的使用时机
时间Fri Mar 18 19:52:52 2022
自己碰到了才有感觉, 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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1647604378.A.411.html
1F:推 Schottky: 把 buffer 读出来丢光 +1 03/18 20:41
2F:推 wei115: 缓冲区有够难搞的= = 读出来丢掉真的是最可靠的 另外用 03/18 22:45
3F:→ wei115: %*[^\n]%*c比较炫泡 03/18 22:45
4F:→ wei115: 当初刷uva被缓冲区冲康很多次 03/18 22:46