<分区>
所以我想知道如果用户在整数变量中输入字符会发生什么,例如:
main()
{
int number;
printf("Print a number:");
scanf(" %d", &number);
printf("The result is:%d", number);
return 0;
}
我输入字符,结果是:1986895412
这个 1986895412 是 ram 中的一个地方吗??
标签 c unix initialization scanf
<分区>
所以我想知道如果用户在整数变量中输入字符会发生什么,例如:
main()
{
int number;
printf("Print a number:");
scanf(" %d", &number);
printf("The result is:%d", number);
return 0;
}
我输入字符,结果是:1986895412
这个 1986895412 是 ram 中的一个地方吗??
最佳答案
在这种情况下,scanf
指令会失败。引用 this answer (本质上改写了规范的定义):
The %d conversion specifier expects the input text to be formatted as a decimal integer. If it isn't, the conversion fails and the character that caused the conversion to fail is left in the input stream.
因此,number
保持与指令之前相同的值。由于您没有使用某个定义的值(如 int number = 0
)对其进行初始化,因此它只是一些随机的垃圾值。在您的情况下,它恰好等于 1986895412
。
关于c - 如果 C 试图扫描整数变量中的字符会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20655381/