Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

c - getc Vs getchar Vs Scanf for reading a character from 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...