C语言 getc Vs getchar Vs Scanf 用于从标准输入读取字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2507082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getc Vs getchar Vs Scanf for reading a character from stdin
提问by Jay
Of the below three functions:
以下三个函数中:
getc getchar & scanf
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?
这些功能中的任何一个是否有任何已知的缺点或限制,使一个比另一个更好?
回答by caf
If you simply want to read a single character from stdin, then getchar()is the appropriate choice. If you have more complicated requirements, then getchar()won't be sufficient.
如果您只是想从 stdin 读取单个字符,那么getchar()是合适的选择。如果您有更复杂的要求,那就getchar()不够了。
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.
getc()允许您从不同的流中读取(例如,以 开头的流fopen());scanf()允许您一次阅读多个字符。
The most common error when using getchar()is to try and use a charvariable to store the result. You need to use an intvariable, since the range of values getchar()returns is "a value in the range of unsigned char, plus the single negative value EOF". A charvariable doesn't have sufficient range for this, which can mean that you can confuse a completely valid character return with EOF. The same applies to getc().
使用时最常见的错误getchar()是尝试使用char变量来存储结果。您需要使用一个int变量,因为getchar()返回值的范围是“范围内的值unsigned char,加上单个负值EOF”。一个char变量没有足够的范围,这一点,这可能意味着你可以混淆一个完全有效的字符回报EOF。这同样适用于getc().
回答by Dchris
from Beej's Guide to C Programming
All of these functions in one way or another, read a single character from the console or from a FILE. The differences are fairly minor, and here are the descriptions:
getc() returns a character from the specified FILE. From a usage standpoint, it's equivalent to the same fgetc() call, and fgetc() is a little more common to see. Only the implementation of the two functions differs.
fgetc() returns a character from the specified FILE. From a usage standpoint, it's equivalent to the same getc() call, except that fgetc() is a little more common to see. Only the implementation of the two functions differs.
Yes, I cheated and used cut-n-paste to do that last paragraph.
getchar() returns a character from stdin. In fact, it's the same as calling getc(stdin).
所有这些功能都以一种或另一种方式从控制台或文件中读取单个字符。差异相当小,以下是说明:
getc() 从指定的 FILE 返回一个字符。从使用的角度来看,它等同于相同的 fgetc() 调用,而 fgetc() 更常见一些。只是这两个函数的实现不同。
fgetc() 从指定的 FILE 返回一个字符。从使用的角度来看,它等同于相同的 getc() 调用,只是 fgetc() 更常见一些。只是这两个函数的实现不同。
是的,我作弊并使用剪切粘贴来完成最后一段。
getchar() 从标准输入返回一个字符。其实和调用getc(stdin)是一样的。

