Roman A. Taycher
Roman A. Taycher

Reputation: 19477

Is there any reason to use scanf or fscanf over fgets+sscanf

Since you're not reading from the stream it seems much more flexible. Both to mention that since you can easily change the timing/code location of the reads then you can with a c stream(am I wrong, can you make strings, ect into c FILE * streams)?

Plus, I don't know I just feel a bit odd about scanf. Any pros/cons to scanf would be appreciated.

Edit: I meant the use of scanf or fscanf vs the combo of fgets+sscanf

Upvotes: 0

Views: 3144

Answers (2)

lovesh
lovesh

Reputation: 5401

If you were expecting an integer but you read a floating point or some other incompatible type, you can check the return value of scanf. If it returns zero, then you didn't read an integer - but with fgets you can't do that. Also, by checking the return value of scanf you can see the number of items read.

Upvotes: 1

cnicutar
cnicutar

Reputation: 182649

This is well addressed in the C FAQ.

Why does everyone say not to use scanf? What should I use instead?

If you are reading from a trusted file (NOT stdin), there's no point in using fgets + sscanf instead of fscanf. Indeed using scanf (reading from stdin) is problematic.

Upvotes: 2

Related Questions