我不明白函数 getline
在这里是如何工作的。为什么换行符被排除在 for 循环之外以及为什么要在单独的 block 中测试换行符是否存在?
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* print the longest input line */
main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* 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("%s", 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 big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
最佳答案
getline
将从 stdin
读取一行。由于行由换行符('\n'
字符)分隔,因此 getline
将读取换行符(包括换行符)。 getline
读取换行符之后的内容是没有意义的,因为它会读取不止一行。
三种情况会导致for循环停止。
1) 遇到 \'n'
。
如果发生这种情况,它将在添加 null 之前将换行符添加到当前字符串的末尾终结者。这就是 if (c == '\n')
的用途。
2) 读取 EOF 或 3) 读取要读取的最大字符数。
如果发生其中任何一种情况,则将跳过在字符串末尾添加换行符,而仅添加空终止符。
空终止符('\0'
字符)是 C 指示字符串结尾的方式。
关于c - getline() 函数在这里如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18278240/