我运行了这段代码
#include <stdio.h>
int main()
{
int u;
scanf("%d",&u);
printf("%d\n",u,u);
return 0;
}
以下是输入和输出:
input:a output:32765
input:b output:32765
input:c output:32767
input:/ output:32766
谁能解释这种行为?
当scanf()
读取输入时,它无法根据规范进行转换,它将停止扫描并返回成功转换的次数。在您的情况下,字符保留在标准输入缓冲区中并scanf()
返回0
。
您的代码具有未定义的行为,因为scanf()
无法将输入转换为整数,而未u
初始化。将此未初始化的值传递给printf
具有未定义的行为。在您的情况下,会打印一些随机值,该值可能不同也可能不同,但是任何其他行为(包括崩溃)都是可能的。
您必须测试的返回值scanf()
以检查转换是否成功。这是修改后的版本:
#include <stdio.h>
int main(void) {
int u, res;
res = scanf("%d", &u);
if (res == 1) {
/* conversion succeeded */
printf("%d\n", u);
} else
if (res == 0) {
/* conversion failed */
printf("input is not a valid number\n");
} else {
/* res must be EOF */
printf("premature end of file: no input given\n");
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句