c - getline() 函数在这里如何工作?

标签 c function getline

我不明白函数 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/

相关文章:

sql - yacc/lex 上的先前标记

c - 如何使用 _Generic 定义通用函数以在 C 中接受输入?

php - 静态关键字在 PHP 生成器函数中不起作用

c - 处理函数中的偏移量

c# - 使所有表单都可以访问表单功能

c++ - 如果用户输入的输入大于 char 数组,cin.getline 会跳过输入提醒

c++ - 如何使 'string line' 与 'getline(in,line)' 循环中的 'while(getline(...))' 在同一范围内?

c# - 按顺序获取文件中的行的最佳方法?

CreateThread 包装函数

c - 什么是 alloc.h?