c - 为什么 printf 打印的大小超过数组的大小?
问题描述
char ad[8];
char ct[40];
printf("postal code: ");
scanf(" %[^\n]7s", ad);
printf("city: ");
scanf(" %[^\n]40s", ct);
printf("Address: |%s|%s\n", ad, ct);
广告的示例输入:m2r 3r3 t4t
。输出应该是:m2r 3r3
。但输出是:m2r 3r3 t4t
解决方案
如果您的意图是读取 7 个字符并丢弃其余输入,您可以执行以下操作:
char ad[8];
char ct[40];
printf("postal code: ");
scanf("%7s%*[^\n]", ad);
printf("city: ");
scanf("%40s%*[^\n]", ct);
printf("Address: |%s|%s\n", ad, ct);
将%7s
读取 7 个字符。并且%*[^\n]
将读取到行尾并丢弃结果。
只是为了强调,我不提倡使用scanf()
,但如果你真的想要上面的代码就可以了。
推荐阅读
- terraform - 使用 Terraform 在 EC2 上设置环境变量的最佳方法?
- c++ - 如何在 Visual Studio Code (VSCode) 中创建用于构建和运行 c++ 代码的单独任务
- google-cloud-dataflow - 数据流模板使用PublicIps 作为参数
- javascript - 反应函数之间的区别
- docker - 在 docker 上设置代理
- reactjs - 有没有一种方法可以浅渲染使用 react-apollo 查询的反应组件
- python - Django select_related 什么都不做
- ios - 添加约束后如何让UILabel上的文字出现在左上角?
- database - 如何在仅带有 ID 的第三个表中显示两个表中的区域和车站名称?
- javascript - 变量的值从何而来?