getc 与 getchar 与 Scanf 从 stdin 读取字符
以下三个函数中:
getc 获取字符& scanf
是从 stdin 读取字符的最佳选择,为什么?
这些功能中的任何一个是否存在任何已知的缺点或限制,从而使其中一个功能优于另一个功能?
Of the below three functions:
getc
getchar &
scanf
which is the best one for reading a character from stdin and why?
Are there any known disadvantages or limitations for any of these functions which makes one better than the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想从标准输入读取单个字符,那么 getchar() 是合适的选择。如果您有更复杂的要求,那么
getchar()
就不够了。getc()
允许您从不同的流中读取(例如,使用fopen()
打开的流);scanf()
允许您一次读取多个字符。使用 getchar() 时最常见的错误是尝试使用 char 变量来存储结果。您需要使用
int
变量,因为getchar()
返回的值范围是“unsigned char
范围内的值,加上单个负值EOF
”。char
变量没有足够的范围来实现此目的,这可能意味着您可能会将完全有效的字符返回与EOF
混淆。这同样适用于getc()
。If you simply want to read a single character from stdin, then
getchar()
is the appropriate choice. If you have more complicated requirements, thengetchar()
won't be sufficient.getc()
allows you to read from a different stream (say, one opened withfopen()
);scanf()
allows you to read more than just a single character at a time.The most common error when using
getchar()
is to try and use achar
variable to store the result. You need to use anint
variable, since the range of valuesgetchar()
returns is "a value in the range ofunsigned char
, plus the single negative valueEOF
". Achar
variable doesn't have sufficient range for this, which can mean that you can confuse a completely valid character return withEOF
. The same applies togetc()
.来自 Beej 的 C 编程指南
from Beej's Guide to C Programming