【发布时间】:2020-02-01 14:42:22
【问题描述】:
我正在学习 C,我偶然发现了一个错误,我似乎无法理解它。
此代码应该接受多行文本(后跟 Enter),将各行相互比较,在遇到 EOF(又名 crtl - Z)时停止比较,选择最长的字符串并将其打印到控制台。
它会这样做,但是在打印出文本时,它有时会在输出中添加一些额外的字符。
这是代码:
int get_line(char s[]);
void copy(char from[], char to[]);
main()
{
int len;
char line[1000]; //the array which is used to compare
char longest[1000]; //the array in which the longest line will be stored
int max = 1; //the maximum length of a line
while ((len = get_line(line)) > 0) //checks if the length of a line in more than 0
if (len > max)
{
max = len;
copy(line, longest);
}
if (max > 0)
printf("%s", longest); //prints out the longest line, if it exists
}
int get_line(char s[])
{
int c, i;
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) //reads the line until ^Z of Enter
s[i] = c;
return (i);
}
copy(char from[], char to[])
{
for (int i = 0; from[i] != '\n'; ++i)
to[i] = from [i];
}
【问题讨论】:
-
如果没有阅读您的代码,这几乎总是意味着您无法在某处对字符串进行空终止。
-
您希望
'\n'在您的代码中的哪个位置输入数组? -
是的,看看
get_line()。 -
就我对C的理解,我认为
'\n'是在getchar()函数中按Enter键进入的。 -
您在
copy中遇到了类似的问题:它应该在达到终止空值时停止,并确保空值终止副本。 (或者重写以使用标准strcpy()。)我还必须指出您的代码存在安全漏洞:如果一行超过1000 个字符,它将溢出您的缓冲区。我理解在开始时希望保持简单,但避免养成坏习惯也很重要。