CodeFu
CodeFu

Reputation: 165

Taking input of char* in array of struct

struct student
{
       char *name;
       int roll_no;

};

student s1[3];

for(int i=0;i<3;i++)
{
        cout<<"Enter name: ";
        cin.getline(s1[i].name,'\n');
        cout<<"\nEnter roll number : ";
        cin>>s1[i].roll_no;        

}  

I want to take full name input in "char* name", but this is not working I know , I can use string but is there any way to do this with char* ?

Upvotes: 1

Views: 1509

Answers (1)

kvorobiev
kvorobiev

Reputation: 5070

In struct student you define pointer to char, but does not allocate memory for it. You need something like

#define STRSIZE 255
struct student
{
       char name[STRSIZE];
       int roll_no;

};
...
cin.getline(s1[i].name, STRSIZE);
...

And second arg to getline is length of input buffer, not delimiter.

Upvotes: 2

Related Questions