Details-
I am taking input of n students
Their number- rollno./mobile/UID in union, their full name, their course name, their age, their branch name.
I am using a linked list to store the data in a sorted manner. As soon as I insert a node, the list becomes sorted simultaneously. In the end, I print the whole list. The list is sorted by age of the candidates.
Can someone please help me why am I getting a runtime error while taking the string input in this program. What should I correct so that the program does not give a runtime error. Thanks in advance.
#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;
}
}