我需要将输入的字符串转换为结构数组。 输入模式是: 城市年龄_1名称_1,年龄_2名称_2,.....年龄_n名称_n城市结束。
我的结构:
typedef struct Node{
int age;
char name[30];
}Node;
我可以为所有数据动态分配一个结构体数组吗? 字符串长度未知!
最佳答案
首先获取城市名称。然后你得到2个输入 scanf("%s",&s) . Now check whether
is end of city. If not then covert it to a
int` 并获取变量中的名称。
现在您维护一个节点列表。每当你得到 age
和name
您创建一个节点并将其添加到列表中。
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;
}
}
关于c - 动态输入字符串,长度未知,并转换为c语言想要的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29213574/