1
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* ?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Correct, but please god no this is terrible. Use std::string. The only reason to do this is to practice how not to do it. And, perhaps, if you're writing a library for C ... but the question is tagged c++!
@Lightning Racis in Obrit I now how work with std::string. Just show the error in the authors code.
Yes, I understood that
@CodeLearner What exactly not working? Please, provide more information

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.