基本上,我已经启动一个程序来读取元素列表,就像
21515 - Water Fire
20215 - Green Banana
87654 - Sun and Moon
...
我的问题是,我想在空白行之后以不同的格式读取我的标准输入:
21515 - Water Fire
20215 - Green Banana
87654 - Sun and Moon
20215 - 1 - 3 - 5 - 4 - SUN1
21515 - 1 - 3 - 5 - 4 - SUN2
所以我必须以某种方式进行更改,是否需要创建一个新列表?如果是这样,我将如何在空白行之后开始阅读新列表?同样,数据与列表的第一部分中的第一数字相关联,与第二部分中的第一部分相关联。有帮助吗?
所以我创建了以下结构和列表
typedef struct struct_data_uc{
int uc_number; // Changed from int *
char *uc_name;
} S_data_uc;
typedef struct List_uc_data{
S_data_uc uc_data;
struct List_uc_data *next;
} L_uc_data;
为列表分配了功能以释放列表并从标准输入中读取数据
// Allocate a new L_uc_data and insert into list
L_uc_data* UC_add(L_uc_data *list, int number, const char *name)
{
L_uc_data *new = malloc(sizeof(L_uc_data));
if (new != NULL) {
new->uc_data.uc_number = number;
// Need strdup here to alloc mem and copy
//new->uc_data.uc_name = strdup(name);
new->uc_data.uc_name =(char*)malloc(strlen(name)+1);
strcpy(new->uc_data.uc_name,name);
new->next = list;
return new;
}
return list;
}
// Free the entire list
void UC_free(L_uc_data *list)
{
while (list) {
L_uc_data *aux = list->next;
// Free the mem from strdup
free(list->uc_data.uc_name);
free(list);
list = aux;
}
}
// Reads the entire file and returns a new list
L_uc_data * UC_read(FILE *f)
{
char line[MAXSTR];
L_uc_data *the_list = NULL;
// Using fgets to get the entire line, then parse
while (fgets(line, MAXSTR, f)) {
int number;
char name[MAXSTR];
// Remember to check the return from sscanf
if (2 == sscanf(line, "%d - %[^\n]", &number, name)) {
// Add to list
the_list = UC_add(the_list, number, name);
}
}
return the_list;
}
然后我打印进行检查
// Print the entire list
void UC_show(L_uc_data *list, FILE *fout)
{
int number_char=0;
while (list) {
fprintf(fout, "%d -> %s\n", list->uc_data.uc_number, list->uc_data.uc_name);
list = list->next;
}
}
我的主要是一个简单的函数调用
int main()
{
L_uc_data *list = UC_read(stdin);
UC_show(list, stdout);
UC_free(list);
return 0;
}
解决的问题创建了一个新结构并分配了列表