First, you shouldn't use scanf_s()
. Microsoft's compiler is telling you to use it, but it's really best to ignore this. While scanf_s()
was designed to be "more secure" by requiring buffer sizes for c
, s
and [
conversions, it was a proprietary Microsoft extension, so using it, you're locked in to Microsoft compilers. Your actual problem is that you don't pass a buffer size in your call, scanf_s()
assumes that &Numbertwo
is the buffer length.
The situation is even worse since the C standard also includes a scanf_s()
. The standard version expects the buffer size to be given as an element count as an rsize_t
, while the Microsoft version expects a byte count as an unsigned
, so they are subtly incompatible! IMHO, this whole function is unnecessary anyways, just using field widths allows you to write secure code with plain scanf()
.
Because scanf()
isn't well-suited for recovering from parsing errors, you shouldn't use it directly for interactive input, instead read a whole line and parse that (for example with sscanf()
). Your code could then look like this:
int Numberone = 0, Numbertwo = 0;
char Op;
char line[512];
if (!fgets(line, sizeof line, stdin))
{
// error reading ...
}
if (sscanf(line, "%d %c %d", &Numberone, &Op, &Numbertwo) != 3)
{
// error parsing ...
}
handle errors accordingly.