gpt4 book ai didi

c - 当我在 scanf 中输入字符而不是整数值时出现意外结果

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:17 25 4
gpt4 key购买 nike

这是我的代码,我遇到了有关 c 中数据类型的问题

#include<stdio.h>
int main()
{
int a,b;
scanf("%d",&b);
printf("%d",b);
}

当输入任何字符而不是整数值时,它总是打印 32。我不明白为什么要打印 32。

最佳答案

打印的值完全是任意的。这是未定义行为的结果,因为 b 仍未分配。

在继续之前,您需要检查用户是否输入了值。 scanf 返回它已处理的项目数,因此您的代码不应使用该值,除非 scanf 已返回 1,表示一个项目已读取成功:

int b;
for (;;) { // Repeat forever
int numRead = scanf("%d",&b);
if (numRead == 1) {
// We've got our number; end the loop:
break;
}
printf("You did not enter a number\n");
// Consume the data that cannot be interpreted as a number.
// Asterisk means "discard the value":
scanf("%*s");
}
printf("b=%d\n", b);

Demo.

关于c - 当我在 scanf 中输入字符而不是整数值时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25714775/

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