简体   繁体   English

Visual Studio 2013中scanf_s和printf中的C计算器错误

[英]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将数据读入char *wchar_t * ,必须指定接受输入的缓冲区的大小。

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

Source: MSDN on scanf_s . 来源: MSDN上的scanf_s

(Note: scanf_s is an optional extension to the Standard C library described in C.11 Annex K.3.5.3.4.) (注意: scanf_s是对C.11附件K.3.5.3.4中描述的标准C库的可选扩展。)


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 . 马特指出"%f"是不正确的格式说明&Pre ,由于Preint ,和"%f"指示参数将是一个指向float Use "%d" to indicate the argument is a pointer to int . 使用"%d"表示参数是指向int的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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