我编写了一个代码,将文件中的内容保存到链接列表中。 不过我想提取年龄并将它们保存到 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/