c++ - 为什么在struct中使用字符串时出现运行时错误

标签 c++ string struct

细节-
我正在录取n名学生
他们在 union 中的号码rollno./mobile/UID,他们的全名,他们的类(class)名称,他们的年龄,他们的分支名称。
我正在使用链表以排序的方式存储数据。一旦插入节点,该列表就会同时进行排序。最后,我打印了整个列表。该列表是,按候选人年龄排序。
有人可以帮助我,为什么在此程序中输入字符串时却出现运行时错误。我应该纠正些什么,以便程序不会出现运行时错误。提前致谢。

#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;
不要在C++程序中使用malloc。原因是malloc不会为其分配的对象调用构造函数。 std::string有一个构造函数,必须调用该构造函数,否则会出错。
您应该做的第二件事是更换工会。当对象具有构造函数时,很难将它们放置在联合中。原因是联合中只有一个对象在任何时间都处于 Activity 状态,因此构造了哪个对象? C++允许您将带有构造函数的对象放在联合中,但是您必须自己处理此类对象的构造。这是一个相当高级的主题,我的建议是简单地删除并集,然后将rollmobileother直接放置在node结构中。但是,如果您想进行一些研究,则应该研究std::variant,这是一个并集的替代品,或者是研究新的放置,这是用于手动构造对象的技术。

关于c++ - 为什么在struct中使用字符串时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63878357/

相关文章:

javascript - 创建一个函数,将字符串格式化为始终在小数点后显示两位有效数字,而不使用方法

c++ - Valgrind: "Invalid read"与 c_str 和 strtod

c - 当我尝试定义结构的元素时,我不断收到错误消息

c++ - 线程在 while 循环中卡住

C++ 编译器优化丢弃模板特化

user-interface - 文本编辑器一般是如何实现的?

json - 在特定结构中解码 Json 数据

c - 当在 DLL 或 .so 中调用函数时,当编译器使用对齐和填充进行自己的结构布局时,为什么传递结构是可靠的?

c++ - 在 isocpp.org 中是否有其他方法可以执行此示例?

c++ clock_gettime()溢出了吗?