在标准输入中使用 fflush() 是非法的吗?该怎么办? [英] Illegal to use fflush() in stdin? What to do instead?

查看:38
本文介绍了在标准输入中使用 fflush() 是非法的吗?该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);

如果没有 fflush(),如果你输入一个字符,说a",然后按回车,输入缓冲区包含a\n",getchar() 偷看a",但\n" 保留在缓冲区中,因此下一个 fgets() 将找到它并返回一个空字符串,甚至无需等待用户输入.

Without the fflush(), if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar() peeks the "a", but the "\n" remains in the buffer, so the next fgets() will find it and return an empty string without even waiting for user input.

应该怎么做?据我所知,在输入流上使用 fflush() 不是定义或标准的吗?

What should be done instead? As far as i know, it's not defined or standard to use fflush() on an input stream?

推荐答案

当您的意图是读取一行输入并解释其中的一个字符时,不要使用 getchar.在这种情况下,读取带有 fgets 或类似内容的一行,然后检查第一行.

Don't use getchar when your intent is to read a line of input and interpret one character from it. In this case, read a line with fgets or similar and just inspect the first line.

或者,您可以坚持使用 getchar,但是您需要继续读取字符直到行尾,然后在继续之前将其丢弃.

Alternatively, you can stick with getchar, but then you need to keep reading characters until the end of the line and throw them away before moving on.

您的程序可以转换为(第一种方法):

Your program could be transformed to (first approach):

char c;
char s[32];
puts("Type a char");
fgets(s,32,stdin);
c=s[0];
puts("Type a string");
fgets(s,32,stdin);

请注意,这缺少对返回值的检查,并且不会处理超过 32 个字节的输入,但这是一个开始,您可以处理这些单独的问题.

Note that this is missing checking of return values and doesn't handle input longer than 32 bytes, but it's a start and those are separate issues you can work on.

这篇关于在标准输入中使用 fflush() 是非法的吗?该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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