c - fscanf 到链接列表

标签 c linked-list malloc

我的代码再次遇到麻烦。
我想要 fscanf result.txt 到带有链表的结构,但它不起作用; 我认为简单链表就足够了;

问题是:程序只写了第一行,没有其他内容。

结果.txt格式:

point name (for examples)
623   john
457   peter
312   chuck
etc.

代码:

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct ranklist {
        int point;
        char* name;
        struct ranklist *next;
    } ranklist;

    int how_many_records(FILE *fp){
        char ch;
        int line=0;
        int status;

        rewind(fp);
        while((status=fscanf(fp, "%*d %*[^\n]%c", &ch))==1)
            ++line;
        if(status != EOF){
            ++line;
        }
        rewind(fp);

        return line;
    }

    int how_many_letter(FILE *fp){
        int letter = 0;
        long pos = ftell(fp);

        //fscanf(fp, " %*[^\n]%n", &letter);
        fscanf(fp, " %*s%n", &letter);
        fseek(fp, pos, SEEK_SET);

        return letter;
    }

    int main(void){
        FILE *fp = fopen("result.txt","r");
        int name_length;
        int lines = how_many_records(fp);
        ranklist *r = malloc(lines * sizeof(*r));
        ranklist *first = r;


        for ( r=first  ;r != NULL; r = r->next){
            fscanf(fp, "%d", &(r->point));
            name_length = how_many_letter(fp);
            r->name = malloc(name_length + 1);
            fscanf(fp,"%s", r->name);
        }

        fclose(fp);

        for ( r=first  ;r != NULL; r = r->next){
            printf("%d %s\n", r->point, r->name);
        }
        free(r);

        return 0;
    }

最佳答案

fscanf(fp, "%d", &r[y].point);

此处,y 未初始化。

您需要输入y = 0,或者,IMO,最好使用&(r->point) [对于r[也是如此y].name 也]

建议:为了更好地读取和解析整行,请使用 fgets()

关于c - fscanf 到链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27268683/

相关文章:

php - 在 PHP 应用程序中使用 C 进行计算 : is it worth it?

c - 如何替换结构中字符串中的字符?

c - 使用 strtok_r 进行字符串解析

python - 在 lldb python 中打印结构数组

c - C 中的链表 : What happens when we assign the current node to a temporary node pointer?

c - 如何在访问链表中的下一个时修复段错误错误?

c++ - 在另一个类中使用类函数

根据用户输入构造二维数组的正确方法

c - 使用malloc动态创建字符串数组

c - 将 char 数组中的信息放入动态创建的数组中