【发布时间】:2023-10-02 14:00:01
【问题描述】:
编程新手,通过 K&R 工作。使用标准输入输入后,我按 ^D 写入 EOF(我正在使用 linux),然后......什么也没有发生。我仍然可以写入控制台,并且可以 ^Z 挂起,但不能使用 ^D。我希望我的代码能够读取输入并打印比要求更长的所有行,并且由于我无法产生任何输出,我不确定从哪里开始诊断我的问题。
/*
Exercise 1-17 in K&R: page 31 in book
Write a program to print all input lines that are longer than 80 characters
*/
# include <stdio.h>
# define MIN_LINE 5 /*change to 80 for final*/
# define MAX_LINE 20 /*change for final*/
int getline(char line[], int max);
void copy(char to[], char from[], int position);
int main()
{
char line[MAX_LINE];
int len = 0;
char print_register[MAX_LINE];
int reg_index = 0;
/*read length of line*/
while ((len = getline(line, MAX_LINE)) != EOF)
{
/*if len > 80; append to print-array*/
if (len > MIN_LINE)
{
copy(print_register, line, reg_index);
}
}
/*print the print-array*/
printf("%s", print_register);
return 0;
}
int getline( char line[], int max)
{
int i;
int c;
for (i = 0; (c = getchar()) != EOF && c != '\n' && i <= max; i++)
{
line[i] = c;
}
/* handle '\n' and EOF */
if (c == '\n')
{
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
void copy(char to[], char from[], int position)
{
int i;
while ((to[position] = from[i]) != '\0')
{
i++;
position++;
}
}
【问题讨论】:
-
因为 getline() 永远不会返回 EOF。它返回“i”。
-
你溢出了
getline中的缓冲区:把for改成for (i = 0; (c = getchar()) != EOF && c != '\n' && i < max; i++) -
@BLUEPIXY:哎哟!非常感谢!
标签: c eof kernighan-and-ritchie