简体   繁体   English

可以使用fseek(stdin,1,SEEK_SET)或倒带(stdin)来刷新输入缓冲区而不是非便携式fflush(stdin)吗?

[英]Can fseek(stdin,1,SEEK_SET) or rewind(stdin) be used to flush the input buffer instead of non-portable fflush(stdin)?

Since I discovered fflush(stdin) is not a portable way to deal with the familiar problem of "newline lurking in the input buffer" ,I have been using the following when I have to use scanf : 由于我发现fflush(stdin)不是处理熟悉的“新行潜伏在输入缓冲区”的问题的可移植方法,所以当我必须使用scanf时,我一直在使用以下内容:

while((c = getchar()) != '\n' && c != EOF);

But today I stumbled across this line which I had noted from cplusplus.com on fflush : 但今天我偶然发现了我在cflplus.com上关于fflush注意到的这一行:

fflush()...in files open for update (ie, open for both reading and writting), the stream shall be flushed after an output operation before performing an input operation. fflush()...在打开以进行更新的文件中(即,打开以进行读取和写入),在执行输入操作之前,应在输出操作之后刷新流。 This can be done either by repositioning (fseek, fsetpos, rewind) or by calling explicitly fflush 这可以通过重新定位(fseek,fsetpos,倒带)或通过显式调用fflush来完成

In fact, I have read that before many times.So I want to confirm if I can simply use anyone of the following before the scanf() to serve the same purpose that fflush(stdin) serves when it is supported: 事实上,我已经多次阅读过了。所以我想确认一下我是否可以在scanf()之前使用以下任何一个来实现与fflush(stdin)支持时相同的目的:

fseek(stdin,1,SEEK_SET);
rewind(stdin);

PS rewind(stdin) seems pretty safe and workable to flush the buffer, am I wrong? PS rewind(stdin)似乎非常安全,可以刷新缓冲区,我错了吗?

Mistake I should have mentioned fseek(stdin,0,SEEK_SET) if we are talking about stdin as we can't use any offset other than 0 or one returned by ftell() in that case. 错误我应该提到fseek(stdin,0,SEEK_SET)如果我们正在讨论stdin因为我们不能使用除0之外的任何偏移或者在这种情况下由ftell()返回的偏移量。

This is the only portable idiom to use: 这是唯一可以使用的便携式习语:

while((c = getchar()) != '\n' && c != EOF);

Several threads including this one explain why feesk won't usually work. 包括这个在内的几个主题解释了为什么feesk通常不会起作用。 for much the same reasons I doubt rewind would work either, in fact the man page says it is equivalent to: 出于同样的原因,我怀疑rewind也会起作用,实际上man page说它相当于:

(void) fseek(stream, 0L, SEEK_SET)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM