细节-
我正在录取n名学生
他们中号- rollno./mobile/UID工会,他们的全名,他们的课程名,他们的年龄,他们的分行名称。
我正在使用链表以排序方式存储数据。一旦插入节点,该列表就会同时进行排序。最后,我打印了整个列表。该列表按候选人年龄排序。
有人可以帮我一下,为什么在此程序中输入字符串时却出现运行时错误。我应该纠正些什么,以便程序不会出现运行时错误。提前致谢。
#include<bits/stdc++.h>
using namespace std;
typedef struct Node node;
struct Node
{
union number
{
string roll;
long long int mobile;
string other;
}id;
string name;
string course;
int age;
string branch;
node *next;
int type;
};
node *head=NULL;
int main()
{
int n;
cout<<"Enter the number of students: ";
cin>>n;
char ch;
string roll;
for(int i=1;i<=n;i++)
{
node *temp=(node*)(malloc(sizeof(node)));
cin>>ch;
if(ch=='R')
{
cin>>temp->id.roll;
temp->type=0;
}
else if(ch=='M')
{
cin>>temp->id.mobile;
temp->type=1;
}
else if(ch=='O')
{
cin>>temp->id.other;
temp->type=2;
}
getline(cin,temp->name);
getline(cin,temp->course);
cin>>temp->age;
getline(cin,temp->branch);
if(head==NULL)
{
head=temp;
head->next=NULL;
continue;
}
if(head->age>=temp->age)
{
temp->next=head;
head=temp;
continue;
}
node *ptr;
ptr=head;
while((ptr->next)!=NULL&&(ptr->next)->age<temp->age)
{
ptr=ptr->next;
}
temp->next=ptr->next;
ptr->next=temp;
}
node *ptr;
ptr=head;
while(ptr!=NULL)
{
if(ptr->type==0)
{
cout<<ptr->id.roll<<",";
}
else if(ptr->type==1)
{
cout<<ptr->id.mobile<<",";
}
else if(ptr->type==2)
{
cout<<ptr->id.other<<",";
}
cout<<ptr->name<<","<<ptr->course<<","<<ptr->age<<","<<ptr->branch<<endl;
ptr=ptr->next;
}
}
您应该做的第一件事是更换
node *temp=(node*)(malloc(sizeof(node)));
与
node *temp=new node;
不要malloc
在C ++程序中使用。原因是malloc
不会为其分配的对象调用构造函数。std::string
有一个构造函数,必须调用它,否则会出错。
您应该做的第二件事是更换工会。当对象具有构造函数时,很难将它们放置在联合中。原因是联合中只有一个对象在任何时间都处于活动状态,因此构造了哪个对象?C ++允许您将带有构造函数的对象放在联合中,但是您必须自己处理此类对象的构造。这是一种相当先进的话题,我的建议是简单地删除该工会和地点roll
,mobile
并other
直接在node
结构。但是,如果您想进行一些研究,则应该研究std::variant
,这是联合的替代品,或者研究new的放置,这是用于手动构造对象的技术。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句