c - 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
解决方案
您需要将地址传递number
给scanf
:scanf("%d", &number);
当您使用字符串时它起作用的原因是因为 c 中的字符串实际上只是指向 a 的指针char
,并且printf
知道对于字符串,它需要取消引用指针才能到达chars
字符串的。
推荐阅读
- powershell - 如何使用 Powershell 在本地更改 Sharepoint 2019 中多个视图的样式
- rust-tokio - 使用带有侦听器连接的 FramedRead 似乎总是没有准备好
- java - 尝试流式传输到自定义 RTMP 时,DJI Mobile SDK 中出现 LiveStreamManager 错误 -3?
- c# - 重定向登录按钮
- node.js - 我无法启动我的反应服务器..我不知道该怎么办!还删除了缓存并再次安装了节点模块
- python - 将集合转换为可散列类型
- c# - EF Core Exception Microsoft.EntityFrameworkCore.DbUpdateException 不确定为什么会抛出这个异常
- http - 在 Fiddler 中,确定下载资源(如图像、js、css)所花费的时间
- python - 如何在 tkinter 画布上创建文本并更改画布中的文本?
- python - 在创建两个模型之后创建两个模型之间的关系。(Python、Django、SQLite)