In the two approaches, there are several differences in behavior. If you use fgets() + sscanf() , you must enter both values ββon the same line, while fscanf() on stdin (or, what is the same, scanf() ) will read them from different lines if it does not find the second value in the first line entered.
But perhaps the most important differences are related to error handling and the mixing of linear oriented input and field oriented input.
If you read a line that you cannot parse with sscanf() after reading it with fgets() , your program may simply discard the line and move on. However, fscanf() , when it cannot convert fields, leaves all the input in the stream. So, if you were unable to read the input you entered, you have to go and read all the data that you want to ignore.
Another subtle getcha comes if you want to mix field-oriented (ala scanf() ) with lines (like fgets() ) in your code. If scanf() converts an int , for example, it will leave the input stream \n behind (if it is, for example, by pressing the enter key), which will cause a subsequent call to fgets() to return immediately with this character in the input. This is a very common problem for new programmers.
So, although you are correct that you can just use fscanf() like this, you can avoid some headaches by using fgets() + sscanf() .
Fatalerror
source share