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
最佳答案
我使用 fgetc
比使用 scanf
幸运得多,尽管它需要一些额外的代码才能顺利工作,但这只是强调了用户输入的麻烦程度:
char ad[8];
int maxlen = 7; //must be 1 less than array size for terminator
char a = '0';
int count = 0;
while (a != '\n' && count < maxlen) { //read until newline or size limit
a = fgetc(stdin);
ad[count] = a;
count++;
}
if (a == '\n') { //case: user entry < maxlen
buffer[count - 1] = '\0'; //get rid of newline char
}
else { //case: user entry >= maxlen
buffer[count] = '\0'; //terminate the string
do {
a = fgetc(stdin);
} while (a != '\n') //safely flush stdin so next entry works
}
当然,这看起来是一个荒谬的代码量,但你可以将它放在可重用的“getEntry”函数中。另外,如果可能的话,请避免用户输入,尤其是在构建代码时。至少到目前为止,上述内容似乎相当万无一失。这就是我现在正在使用的,因此非常欢迎任何错误发现。
关于c - 为什么 printf 打印的内容大于数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58966357/