我无法为以下代码的输出给出正确的理由。谁能帮帮我。
int main()
{
int i;
char ch;
scanf("%c",&i);
scanf("%d",&ch);
printf("%d\n%c",i,ch);
return 0;
}
输入输出:
input:
a
45
output:
0
-
最佳答案
您正在将 int
读入 char
。假设 sizeof(int) != sizeof(char)
,这将导致 scanf
写入超出 ch
的末尾,并产生未定义的后果。
您应该为 int
参数使用 %i
格式说明符,为 char
参数使用 %c
int main()
{
int i;
char ch;
scanf("%c",&ch);
scanf("%d",&i);
printf("%d\n%c",i,ch);
return 0;
}
关于c++ - 使用 %c 扫描整数,使用 %d 扫描字符 : unexpected results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17862659/