替代到C库函数fflush(标准输入) [英] Alternative to C library-function fflush(stdin)

查看:248
本文介绍了替代到C库函数fflush(标准输入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释下code如何解释,我真的不明白。

 ,而((C =的getchar())='\\ n'和;!&安培;!C = EOF);

我知道,它用来冲洗InputStream和它可以用标准C库函数来代替:

  fflush(标准输入)


解决方案

 ,而((C =的getchar())='\\ n'和;!&安培;!C = EOF) ;

这读取输入的字符,直到它到达该线的末尾(即的getchar()返回的'\\ n )或结束文件或错误条件(即的getchar()返回 EOF

如果标准输入从键盘读取,它丢弃输入直到preSS Enter键。

离开关 EOF 检查可以给你一个无限循环,如果有输入错误,或者如果你触发档案结尾的条件(在Unix上,通过输入<大骨节病>按Ctrl-D 两次)。

这可能是有用的,例如,使用 scanf()的读一个整数后。如果执行 scanf函数(%d个,试验#); 键,键入 123 ,它会读取那些3数字(并存储该值 123 N ),但等待被读取后,放弃一切。以上线路可用于跳过输入行的其余部分。

(另一种方法,可能是一个更好的,是用来阅读整行与fgets()并使用解析它们的sscanf()

这是的的等同于 fflush(标准输入)。一种远为C标准而言,调用 fflush 上的输入流已未定义的行为。

一些实现做定义 fflush(标准输入)的行为。在使用GNU libc的,例如(大多数Linux系统)系统:


  

有关输入流, fflush()丢弃任何具有缓冲数据
  从底层文件被取出,但还没有得到所消耗
  应用程序。


这不是一样丢弃输入到行的结尾。并用它使你的code不可移植。

Can anyone explain how the following code could be explained, I dont understand it really.

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

I know that its used to flush the inputstream and that it could be replaced with the standard C library-function:

fflush(stdin)

解决方案

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

This reads input characters until it reaches either the end of the line (i.e., getchar() returned '\n) or end-of-file or an error condition (i.e., getchar() returned EOF).

If stdin is reading from the keyboard, it discards input until you press Enter.

Leaving off the EOF check could give you an infinite loop if there's an input error, or if you trigger an end-of-file condition (on Unix, by typing Ctrl-D twice).

This could be useful, for example, after using scanf() to read an integer. If you execute scanf("%d", &num); and type 123, it will read those 3 digits (and store the value 123 in n), but leave everything after that waiting to be read. The above line can be used to skip the rest of the input line.

(An alternative, likely a better one, is to read whole lines using fgets() and parse them using sscanf().)

This is not equivalent to fflush(stdin). A far as the C standard is concerned, calling fflush on an input stream has undefined behavior.

Some implementations do define the behavior of fflush(stdin). On systems that use GNU libc, for example (most Linux system):

For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

That's not the same as discarding input up to the end of the line. And using it makes your code non-portable.

这篇关于替代到C库函数fflush(标准输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆