【问题标题】:strcat in C not workingC中的strcat不起作用
【发布时间】:2013-10-16 03:05:18
【问题描述】:

大家好,我正在尝试编写一个函数,该函数返回数据行并将其以字符串形式返回。下面是我的代码,我不确定它为什么不起作用。我已经添加了一个 printf 函数,当我调用该函数时,什么都没有打印出来。?

编辑(因为我还不能回答) - 感谢您的回复。当我将 char c 更改为 char *c 时,它仍然不起作用。我只需要将行读入字符串并返回即可。

char* getLine(FILE *file, int lineNum){

    char c;
    int lineCount=0, size = 1;
    char *line = NULL;
    line = malloc(sizeof(char)*size);
    while ((c=getc(file)) != EOF){

        if (c=='\n'){
            ++lineCount;
            continue;
        }
        if (lineCount==lineNum){
            size += 1;
            line = realloc(line, size*sizeof(char));
            strcat(line, c);
            printf("Line: %s\n", line);
        }
    }
    return line;
}

【问题讨论】:

标签: c strcat


【解决方案1】:

变量c 不是const char * 类型 见strcat documentation

【讨论】:

    【解决方案2】:

    效率不是很高,但它应该做你想做的事:

    注意 lineCount 从 0 开始。(第一行是第 0 行)。

    char* getLine(FILE *file, int lineNum){
        char c;
        int lineCount=0, size = 0; // start size at zero, not one
        char *line = NULL;
    
        while ((c=getc(file)) != EOF){
            if (lineCount==lineNum){
                size += 1;
                if(line == NULL) {
                    line = calloc(sizeof(char), size); 
                } else {
                    line = realloc(line, size*sizeof(char));
                }
                char ac[2] = { c, 0 }; // this line is new
                strcat(line, ac); // ac is new here
                printf("Line: %s\n", line);
                if(c == '\n') {
                    return line;
                }
            }
            if (c=='\n'){
                ++lineCount;
            }
        }
        printf("Could not find line %d\n", lineNum);
        return NULL;
    }
    

    【讨论】:

    • 刚刚回来说谢谢,现在我可以回复了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2015-02-20
    • 2011-08-22
    • 2010-09-29
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    相关资源
    最近更新 更多