c - 为什么 printf 打印的内容大于数组的大小?

标签 c printf scanf

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/

相关文章:

iphone - 在 Objective C 中实例化 C 数组 - 崩溃错误 - 已释放对象的校验和不正确

c - 存储在 C 结构 'magically' 中的值会自行更改

c - 获取格式化字符串到变量

c - 如何检查命令行参数是否为整数

c - 获取多维数组元素时出现段错误

c# - ECDSA 登录 c# 在 c 中验证

c++ - snprintf "date"和文件位置问题

C科学记数法指数格式

c++ - scanf() 奇怪的行为!

c - 使用 cvEigenDecomposition 等时出现 Unresolved external symbol 错误