首页 > 解决方案 > how to use scanf to read an integer from the command line

问题描述

suppose I have the following code:

int number;
scanf("%d", number);
printf("%d", number);

I am entering a number, say 10, as the input, but I am not getting it to print anything. If I change my code so that it scans the input as a string it works fine:

char number[2];
scanf("%s", number);
printf("%s", number);

Am I doing something wrong? And if so, what? I am doing all my work at https://www.onlinegdb.com/online_c_compiler if that changes anything

标签: cscanf

解决方案


您需要将地址传递numberscanfscanf("%d", &number);

当您使用字符串时它起作用的原因是因为 c 中的字符串实际上只是指向 a 的指针char,并且printf知道对于字符串,它需要取消引用指针才能到达chars字符串的。


推荐阅读