首页 > 解决方案 > 为什么 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

标签: cprintfscanf

解决方案


如果您的意图是读取 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(),但如果你真的想要上面的代码就可以了。


推荐阅读