【问题标题】:C Calculator Error in scanf_s and printf with Visual Studio 2013使用 Visual Studio 2013 的 scanf_s 和 printf 中的 C 计算器错误
【发布时间】:2014-11-09 15:48:58
【问题描述】:

我正在尝试制作的计算器应用程序在运行时无法正常工作。它出现了一个奇怪的消息框(见下文)。

#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;
}

有什么想法吗?

【问题讨论】:

    标签: c visual-studio-2012 runtime-error calc


    【解决方案1】:

    当使用scanf_s 将数据读入char *wchar_t * 时,您必须指定接受输入的缓冲区的大小。

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

    来源:MSDN on scanf_s

    (注意:scanf_s 是 C.11 附录 K.3.5.3.4 中描述的标准 C 库的可选扩展。)


    Matt 指出"%f"&amp;Pre 的不正确格式说明符,因为Preint,而"%f" 表示参数将是指向float 的指针。使用"%d" 表示参数是指向int 的指针。

    【讨论】:

    • 另外,%f 用于读取浮点数。 scanf_s("%f", &amp;Pre) 不会工作。使用 %d 作为整数。
    • @MattMcNabb:很好的收获。
    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2016-06-28
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多