简体   繁体   中英

C Calculator Error in scanf_s and printf with Visual Studio 2013

My calculator application I'm trying to make isn't working properly when run. It comes up with a weird message box (see below).

错误

#include <stdio.h>

int main()
{
int Pre;
float v1;
float v2;
char op;

printf("Enter precision: ");
scanf_s("%f", &Pre);

if (Pre < 0)
{
    printf("Error: negative precision\n");
    return 0;
}

printf("Enter expression: ");
scanf_s("%f %c %f", &v1, &op, &v2);

if (op == '+')
{
    printf("%f %c %f\n", v1, op, v2);
    return 0;
}


return 0;
}

Any ideas?

When using scanf_s to read data into a char * or wchar_t * , you must specify the size of the buffer that is accepting the input.

scanf_s("%f %c %f", &v1, &op, 1, &v2);

Source: MSDN on scanf_s .

(Note: scanf_s is an optional extension to the Standard C library described in C.11 Annex K.3.5.3.4.)


Matt points out that "%f" is the incorrect format specifier for &Pre , since Pre is an int , and "%f" indicates the argument will be a pointer to float . Use "%d" to indicate the argument is a pointer to int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM