This question already has answers here:
Closed 7 months ago.
Reading a character with scanf_s
(3个答案)
每当我试图读取表达式(如3 + 5
#include <stdio.h>

add(double a, double b, int prec);

int main() {
    int prec;
    double a, b;
    char oper;

    printf("Enter Precision: ");
    scanf_s("%d", &prec);
    if (prec<0) {
        printf("This is not a valid precision value");
    }
    printf("%d", prec);
    printf("Enter Expression: ");
    scanf_s("%lf %c %lf", &a, &oper, &b);
    …
}

最佳答案

根据MSDN,由于使用scantf_s格式的%c函数,必须指定字符缓冲区长度:
与scanf和wscanf不同,scanf_s和wscanf_s要求为包含在[]中的所有c、c、s、s或字符串控制集的输入参数指定缓冲区大小。缓冲区大小(以字符为单位)作为附加参数传递,紧随指向缓冲区或变量的指针。
所以正确的方法调用是:

scanf_s("%lf %c %lf", &a, &oper, 1, &b);

10-01 19:44