[C] difference between getchar ,scanf etc

  • Thread starter Thread starter jd12345
  • Start date Start date
  • Tags Tags
    Difference
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 8K views
jd12345
Messages
251
Reaction score
2
What is the difference between both? I tried the standard input and output program using both and only found one difference. Using getchar ctrl+D was the end of file but using scanf ctrl+D did not work. So other than this is there any difference.
Also I read there are others like getc etc. What are they used for?
If they all take input from user and do the same job why are there so many functions for the same thing?
 
Physics news on Phys.org


Hi jd12345!

Ctrl+D works the same for all of them - it ends the standard input (on e.g. Linux).

However, there may or may not still be unread input in the input buffer.
getchar() will read the input buffer character by character.
scanf() will scan the input for the fields that you specify.

If you type a couple of characters, getchar() won't read those immediately.
It will only do so when you press Enter, just like all other functions that work on standard input.

If you type a couple of character and the press ctrl+D, getchar() will still read those characters successfully one by one first, before returning EOF.
Similary, scanf() will scan what it can.
Its return value depends on the situation.
If it could not parse anything successfully, it will return EOF.

The other functions like getc() are slightly different again.
getchar() implicity reads from standard input, while getc() will read from the file stream you specify.
 


I like Serena said:
scanf() will scan the input for the fields that you specify.
What do you mean by that?

I understood how getchar works but I am still not clear about scanf.
Also what is the use of so many functions which do more or less similar things? If you could give an example where one of them is more uselful than the other I think it would help explain me better.
Thank you!
 
scanf("%d %d", &i, &j) scans the input buffer.
It will skip white space and try to find digits.
The first group of digits is stored as an integer in "i".
Then the first field will have been successfully scanned.
This is an advanced method to parse input.

getchar() is a shorthand for getc(stdin).
One might say that getchar() is redundant.
It is a low level function.

In particular there is a set of functions that reads implicitly from stdin.
There is another set of functions, prefixed with "f", that reads from a FILE pointer.

Furthermore fgetc() and getc() are equivalent.
I don't know why both of them exist.
The function getc() should have been defined in the place of getchar() to be consistent.

As for examples, see for instance:
http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/

It shows an example how to use fgetc().
Similarly this same website contains an example for each of the other functions.