getc Vs getchar Vs Scanf for reading a character from stdin

后端 未结 2 1810
温柔的废话
温柔的废话 2020-12-02 23:13

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 disadvan

2条回答
  •  孤城傲影
    2020-12-03 00:10

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

提交回复
热议问题