gpt4 book ai didi

c - 为什么 scanf 只返回已成功读取的输入数?

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

我目前正在学习 C 程序,我有一个简单的程序来读取整数输入,代码如下所示:

int main() 
{
int x;
printf("%d",scanf("%d",&x));
/* Suppose that input value given
for above scanf is 45 */
return 1;
}

输出为1

当我尝试这段代码时:

int main() 
{
int x, z;
printf("Enter The Value: ");
int y = scanf("%d %d",&x, &z);
printf("The value is %d", y);
/* Suppose that input value given
for above scanf is 20 789 */
return 1;
}

输出为2

所以这是我的问题,为什么 scanf 只返回输入数量而不是用户输入的?有人可以解释一下它是如何工作的吗?

最佳答案

scanf() 可以处理多个输入 - 在第二个示例中,它将两个输入读取到 xz 中。输入可以是多种不同的类型,但函数的返回值必须指定为特定类型,在本例中为 int

由于 scanf() 将用户输入放入参数中指定的变量中,因此无需将其作为函数值返回。

返回输入的数量可以让您知道它有多成功。如果格式字符串中有两个 %d,但它仅返回 1,则意味着第二个输入看起来不像整数。仅填写xz不会更新。因此,您应该检查返回值是否等于您尝试解析的输入数量,如果不匹配则报告问题。

关于c - 为什么 scanf 只返回已成功读取的输入数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879010/

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