getc Vs getchar Vs Scanf for reading a character from stdin

杀马特。学长 韩版系。学妹 提交于 2019-11-26 15:59:32

问题


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?


回答1:


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.

  • getc() allows you to read from a different stream (say, one opened with fopen());
  • 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 a char variable to store the result. You need to use an int variable, since the range of values getchar() returns is "a value in the range of unsigned char, plus the single negative value EOF". A char variable 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().




回答2:


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).



来源:https://stackoverflow.com/questions/2507082/getc-vs-getchar-vs-scanf-for-reading-a-character-from-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!