首页 > 解决方案 > 谁能告诉我mgetline在做什么?我无法理解

问题描述

我无法理解 mgetline 在此代码中的作用。任何人都可以帮助我吗?

int mgetline(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;
}

标签: calgorithm

解决方案


该函数基本上从标准输入流中一个接一个地读取字符,stdin直到您输入一个(换行符)或达到, ,\n的数组限制。字符存储在 中,并返回读取内容的长度。slimchar s[]

很难更详细地回答,因为有点不清楚你不明白什么,但我尝试对代码进行注释以使其更清晰。

这是相同的代码,只是重新格式化以适合我的评论。

int mgetline(char s[], int lim) {
    int c, i;
    
    for(i = 0;                // init-statement, start with `i` at zero
        i < lim - 1           // condition, `i` must be less than `lim - 1`
        &&                    // condition, logical AND
        (c = getchar()) !=EOF // (function call, assignment) condition, `c` must not be EOF
        &&                    // condition, logical AND
        c != '\n';            // condition, `c` must not be `\n` (newline)
        ++i)                  // iteration_expression, increase i by one
    {
        s[i] = c;             // store the value of `c` in `s[i]`
    }

    if(c == '\n') {           // if a newline was the last character read
        s[i] = c;             // store it
        ++i;                  // and increase i by one
    }
    
    s[i] = '\0';              // store a null terminator last

    return i;                 // return the length of the string stored in `s`
}

在循环的condition一部分中,for您有 3 个条件都必须是true循环进入语句的条件for(...;...;...) statement。我已将该语句放入代码块中,以便更容易查看范围。是输入流 ( ) 关闭时EOF返回的特殊值。getchar()stdin

注意:如果您传递一个包含一个 char( )的数组,lim == 1此函数将导致未定义的行为。任何读取未初始化变量的程序都有未定义的行为——这是一件坏事。在这种情况下, if lim == 1,您将c在循环之后读取,c然后仍将未初始化。

要么初始化它:

int mgetline(char s[], int lim) {
    int c = 0, i;

或退出该功能:

int mgetline(char s[], int lim) {
    if(lim < 2) {
        if(lim == 1) s[0] = '\0';
        return 0;
    }
    int c, i;

推荐阅读