Kernighan 和 Ritchie 问题 1-17 的 Printf 问题
在下面的代码中(Kernighan 和 Ritchie 编写的《C 编程语言》中的问题 1-17)为什么不打印最长的行(在底部)?
#include <stdio.h>
#define MAXLINE 1000
#define LONGLINE 10
int getLineLength(char line[], int maxline){
int i, c;
for(i = 0; i< maxline-1 && (c = getchar() != EOF) && c != '\n'; i++)
line[i] = c;
if(c == '\n') {
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
main() {
int len;
char line[MAXLINE];
while((len = getLineLength(line, MAXLINE)) > 0)
if(len > LONGLINE)
printf("The line was over the maxlength\n\t %s", line);
return 0;
}
In the code below (for problem 1-17 in "The C Programming Language", by Kernighan and Ritchie) why doesn't it print the longest line (at the bottom)?
#include <stdio.h>
#define MAXLINE 1000
#define LONGLINE 10
int getLineLength(char line[], int maxline){
int i, c;
for(i = 0; i< maxline-1 && (c = getchar() != EOF) && c != '\n'; i++)
line[i] = c;
if(c == '\n') {
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
main() {
int len;
char line[MAXLINE];
while((len = getLineLength(line, MAXLINE)) > 0)
if(len > LONGLINE)
printf("The line was over the maxlength\n\t %s", line);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的代码中:
这将被评估为
(c = (getchar() != EOF))
,给出错误的结果。你需要的是:In your code:
This will be evaluated as
(c = (getchar() != EOF))
, giving the wrong result. What you need is:该程序从标准输入读取数据,并打印长度超过 10 个字符的长消息。行以“\n”(换行符、ENTER)结束。如果您输入文件(例如通过管道),则输入以 EOF 结尾;如果您手动输入字符,则输入以 CTRL-C 结尾。
This program reads from standard input, and prints that long message for lines longer 10 than characters. Lines end with '\n' (newline, ENTER). Input ends with EOF, if you feed a file, e.g. through a pipe, or CTRL-C, if you enter characters manually.
我很惊讶这竟然有效。
(c = getchar() != EOF)
从一开始就是完全错误的。line[i] = c;
出现两次。我认为在边缘情况下它很容易受到缓冲区溢出的影响。编辑:我看不到更多的早期答案说你似乎在 for 循环中缺少大括号。
I'm surprised this works at all.
(c = getchar() != EOF)
is completely wrong for a start.line[i] = c;
appears twice. And I think it's vulnerable to a buffer overflow in an edge case.EDIT: An earlier answer that I can't see any more said that you seem to have your braces missing from the for loop.