c - 从字符串中提取整数并将其保存到链表中

标签 c string struct linked-list integer

我编写了一个代码,将文件中的内容保存到链接列表中。 不过我想提取年龄并将它们保存到 int 数组中。 例如,Martha 将存储在 name 中,12 将存储在age 中。

我一直在思考如何实现它,但我无法想出一个合适的解决方案。

下面的代码将 martha 12 存储到 char 数组中。

#include <stdio.h>
#include <stdlib.h> 
#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#define MAXN 50    
#define val 2
typedef struct node {
    char name[MAXN];
    //int value[val];
    struct node *next;
}
node;

int main (int argc, char **argv) {

    FILE *file = argc > 1 ? fopen (argv[1], "r") : stdin;
    if (file == NULL)
        return 1;

    char buf[MAXN];
   // int buf2[val];

    node *first = NULL, *last = NULL;   


    while (fgets (buf, MAXN, file)) {

        node *head = malloc (sizeof(node));
        if (head == NULL) {         
            perror ("malloc-node"); 
            return 1;   
        }


        buf[strcspn(buf, "\n")] = 0;    


        strcpy (head->name, buf);
        head->next = NULL;


        if (!last)
            first = last = head;
        else {
            last->next = head;
            last = head;
        }


    }

    if (file != stdin)  
        fclose(file);

    node *ptr = first;              
    while (ptr != NULL) {           
        node *node_t = ptr;         
        printf ("%s\n", ptr->name); 
        ptr = ptr->next;            
        free (node_t);              
    }

    return 0;
}

这是输入文件:

Martha 12
Bill 33
Max 78
Jonathan 12
Luke 10
Billy 16
Robert 21
Susan 25
Nathan 20
Sarah 22

有什么建议吗? 预先感谢您。

最佳答案

您不需要的数组,只需要int。另外,我会使用大写的 N 作为 typedef 并相应地更改变量声明 (Node *head;)

typedef struct node {
    char name[MAXN];
    int value;
    struct node *next;
} Node;

您应该使用 sscanf 解析字符串并将值分配给 struct,而不是使用 strcpy 复制刚刚读取的行。请注意,我们在引用 head->value 之前放置了 & 运算符,因为我们需要指向 value 的指针:

sscanf(buf, "%s %d", head->name, &head->value);

对于错误处理,您还可以检查返回值的数量:

if(sscanf(buf, "%s %d", head->name, &head->value) != 2) {
    /* Do some error handling */
}

关于c - 从字符串中提取整数并将其保存到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832349/

相关文章:

c - 使用数据结构来处理内存的个人 malloc 函数

C编程: '&' with arrays in scanf

c - 如何在程序执行时创建控制终端?

c - 如何在 Flex 的另一个定义中使用以前的正则表达式定义?

python - Str 在 Dask Dataframe 中拆分并展开

c - 最新的container_of宏中__mptr的用途是什么?

c++ - 'WinMain' 上的注释不匹配(window api)

javascript - 将字符串更改为 javascript 中的函数(不是 eval)

C - 读取一串数字

c - Qsort结构数组比较函数