为什么printf打印的结果大于数组的大小?

问题描述 投票:0回答:2
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

c printf scanf
2个回答
0
投票

fgetcscanf运气好得多,尽管它需要一些额外的代码才能平稳地工作,但这只是强调了麻烦的用户输入可能是:

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``函数中。另外,请尽可能避免用户输入,尤其是在构建代码时。到目前为止,至少到目前为止,以上内容似乎相当简单。这就是我现在正在使用的内容,因此任何发现错误都值得欢迎。


0
投票

如果您打算读取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(),但如果您确实想要上述代码,则可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.