2

I used scanf() in my program,when I compile it I'm getting a lot of warnings regarding use of scanf as follows: D:\myspace\projects\nnf\NNFAdaptor\NNFAdaptor\main.cpp C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.

I also tried using _CRT_SECURE_NO_WARNINGS but it is not present in my Qt (headers),it is shown as error.

Satya Kumar
  • 179
  • 1
  • 4
  • 19

2 Answers2

11

Put #define _CRT_SECURE_NO_WARNINGS at the top of your main.cpp (before any #includes).

Alex
  • 1,082
  • 17
  • 27
4

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:

  1. 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.
  2. It is almost impossible to write a scanf-based input parser that can handle ill-formed input reliably.
  3. 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::strings 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.

zwol
  • 135,547
  • 38
  • 252
  • 361