繁体   English   中英

动态输入字符串,未知长度,并转换为C语言中的所需类型

[英]dynamically String input, unknown length, and convert to the wanted type in c language

我需要将输入的字符串转换为struct数组。 输入模式为:城市age_1 name_1,age_2 name_2,..... age_n name_n end_of_city。

我的结构:

 typedef struct Node{
    int age;
    char name[30];
}Node;

如何为所有数据动态分配结构数组? 字符串的长度未知!

首先获得一个城市名称。 然后,您将获得2个输入scanf(“%s”,&s) . Now check whether . Now check whether s is end of city. If not then covert it to a is end of city. If not then covert it to a int`并在变量中获取名称。

现在,您将维护一个节点列表。 每当您获得agename ,就创建一个节点并将其添加到列表中。

typedef struct Node{
    int age;
    char name[30];
    Node *next;
}Node;

对于分配节点-

Node *head;
void insert(Node *head,int age,char* name)
{
    Node *temp=(Node*)malloc(sizeof(struct Node));
    temp->age=age;
    temp->next=NULL;
    strcpy(temp->name,name);
    Node *t=head;
    if(t==NULL)
    {
        head=temp;
        return;
    }
    else
    {
       while(t->next!=NULL)
         t=t->next;
       t->next=temp;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM