通过scanf_s读取字符时访问冲突写入位置
每当我尝试读取诸如3 + 5
类的表达式时,我一直遇到“访问违规写入位置”
#include 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,由于您使用%c
格式的scantf_s
函数,您必须指定字符缓冲区长度:
与scanf和wscanf不同,scanf_s和wscanf_s要求为包含在[]中的c,C,s,S或字符串控制集类型的所有输入参数指定缓冲区大小。字符的缓冲区大小作为附加传递紧跟在指向缓冲区或变量的指针之后的参数。
所以正确的方法调用将是:
scanf_s("%lf %c %lf", &a, &oper, 1, &b);