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 fs开发者_如何学编程canf vs the combo of fgets+sscanf
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.
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.
精彩评论