为什么在结构中使用字符串时会出现运行时错误

1 c++ string struct

细节-

我正在接受 n 个学生的意见

他们的编号 - rollno./mobile/UID in union,他们的全名,他们的课程名称,他们的年龄,他们的分支名称。

我使用链表以排序方式存储数据。一旦我插入一个节点,列表就会同时排序。最后,我打印了整个列表。该名单按候选人的年龄排序。

有人可以帮助我为什么在此程序中输入字符串时出现运行时错误。我应该更正什么以便程序不会出现运行时错误。提前致谢。

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

joh*_*ohn 5

你应该做的第一件事是更换

   node *temp=(node*)(malloc(sizeof(node)));
Run Code Online (Sandbox Code Playgroud)

   node *temp=new node;
Run Code Online (Sandbox Code Playgroud)

不要malloc在 C++ 程序中使用。原因是它malloc没有为它分配的对象调用构造函数。std::string有一个构造函数,必须调用 this 否则你会得到错误。

您应该做的第二件事是更换工会。当对象有构造函数时,很难将它们放在联合中。原因是任何时候union中只有一个对象是存活的,那么构造了哪个对象呢?C++ 允许您将带有构造函数的对象放在联合中,但您必须自己处理此类对象的构造。这是一个相当高级的话题,我的建议是简单地删除 union 和 place rollmobileother直接在node结构中删除。但是如果你想做一些研究,你应该研究一下std::variant,这是一个联合的替代品,或者研究放置 new,这是手动构造对象的技术。