gpt4 book ai didi

c - scanf_s() 不返回每个输入

转载 作者:行者123 更新时间:2023-11-30 19:07:31 24 4
gpt4 key购买 nike

我编写了一些 C 代码来读取两个数字和一个运算符:

int Numberone = 0, Numbertwo = 0;
char Op;
scanf_s("%d %c %d", &Numberone, &Op, &Numbertwo);

用户输入输入 (5 + 2) 后,变量具有以下值:Numberone = 5、Op = + 和 Numbertwo = 0。但这是错误的。第二个应该是 2。我如何改进我的代码?为什么我的代码是错误的?

最佳答案

您正在使用 scanf_s(请注意 _s),它要求 %s 类型的每个参数都有一个最大长度参数>%c(例如,cppreference.com 上的 scanf_s):

scanf_s: Same as scanf, except that %c, %s, and %[ conversion specifiers each expect two arguments (the usual pointer and a value of type rsize_t indicating the size of the receiving array, which may be 1 when reading with a %c into a single char).

所以你的 %c 格式的参数太少了,它应该是这样的:

scanf_s("%d %c %d", &Numberone, &Op, (rsize_t) 1, &Numbertwo);

关于c - scanf_s() 不返回每个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com