棘手的问题是char longest[]
数组初始化。如果我把它写成 ( char longest[lim]
),EOF 后返回给我的字符串比 长lim
,所以我认为它不会这样工作。但是,如果我明确地将 10 放在那里 ( char longest[10]
) - 它会按我的预期工作并且只返回 10 的第一个字符line
。
int lim = 10; char longest[lim]
在这种情况下,和之间有什么区别?char longest[10]
#include <stdio.h>
#define MAXLINE 1000 //maximum input line size
//#define LIM 10
int getline(char line[], int maxline);
void copy(char to[], char from[]);
//print longest input line
main()
{
int lim=10;
int len; //current line length
int max; //maximum length seen so far
char line[MAXLINE]; //current input line
char longest[lim]; //longest line saved here
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
{
if (len > max)
{
max = len;
copy(longest, line);
}
}
if (max > 0) //there was a line
{
printf("Length: %d\n", max);
printf("First %d characters of line: %s", lim, longest);
}
return 0;
}
//getline: read a line into s, return length
int getline(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
{
s[i] = c;
}
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
//copy: copy 'from' into 'to'; assume to is bigh enough
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
{
++i;
}
}