That class of warnings is mostly wrong (particularly about what to use instead) but it really is true that you should not use scanf
, because:
- It is very easy to write a format specification that is dangerous in the same way that
gets
is dangerous, i.e. it will write past the end of a buffer without noticing. It is possible to write format specifications that don't have this problem but it is much harder.
- It is almost impossible to write a
scanf
-based input parser that can handle ill-formed input reliably.
- Overflow in any numeric conversion is technically undefined behavior, which means the C library is allowed to crash your program just because someone typed too many digits. (Good C libraries will not do anything worse than produce garbage in your result variable, but that can itself be a headache.)
You should not use scanf_s
instead; it attempts to paper over problem 1 but doesn't entirely succeed, and it doesn't address problems 2 and 3 at all. Since you are using Qt, I recommend:
- Read entire lines into
std::string
s using std::getline
.
- Parse them with
QRegExp
.
- Convert numeric strings to numbers with e.g.
QString::toDouble
.
If your input syntax is more complicated than regexes can handle, investigate QLALR
.