Your problem is that scanf_s requires a buffer size specifier after every %c %s and %[. See this post for a similar problem. Indeed, scanf does not have this issue, what you actually did was put the value of the address of num2 as the buffer size specifier for %c
in:
scanf_s("%f %c %f",&num1,&oper,&num2);
Note that even printf_s has additional requirements
The fix here while still using scanf_s is this:
#include <stdio.h>
int main() {
float num1, num2;
int type;
char oper;
const int oper_buff_size = 1;
printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary calculator.\n");
scanf_s("%d", &type);
if (type == 1) {
printf_s("Please enter the equation you want to solve and then press Enter:\n");
// note oper_buff_size, the buffer size of the char pointer
scanf_s("%f %c %f", &num1, &oper, oper_buff_size, &num2);
// test to show this works
printf_s("Entered: %f %c %f", num1, oper, num2);
}
return 0;
}
You may be asking why we need to specify the length of a %c
format, considering it should just be the size of a char in bytes. I believe this is because you are required to put the pointer of a character for format, so you don't know if what you pointed to was a char * array or just a pointer to a char (as in this case)
I would also add an addendum, though this is not why your program failed, avoid using cross platform incompatible quirks, such as void main, as it makes it harder for people to find the real problems in your code. Do not use void main()
, use int main(...) and return 0; instead. Void main is not valid in standard C or C++, it is a quirk of the Microsoft visual studio implementation of the language.