so as the title suggests , I wanted to write a program using structures pointers
to enter n students names and roll numbers ,
so I wrote the program below that worked just fine ..,for a first name
#include<iostream>
usingnamespace std;
struct student
{
char name[20];
int roll_no;
};
int main()
{
int n;
cout<<"enter number of students that you want to enter their info.\n";
cin>>n;
student stu[n],*ptr;
cout<<"enter data \n";
for (ptr=stu;ptr<(stu+n);++ptr)
{cout<<"name:\n";
cin>>ptr->name;
cout<<"roll number:\n";
cin>>ptr->roll_no;}
cout<<"student data:\n";
ptr=stu;
while(ptr<(stu+n))
{ cout<<ptr->name<<" "<<ptr->roll_no<<endl;
ptr++;
}
}
but I wanted a program to enter the full names for n students using structures' pointers, so I tried using gets(ptr->name) , and tried again using cpp styled strings and getline(cin,ptr->name)
those did not work however for more than one name then the program took no more , the codes below:
#include<iostream>
#include<cstdio>
usingnamespace std;
struct student
{
char name[20];
int roll_no;
};
int main()
{
int n;
cout<<"enter number of students that you want to enter their info.\n";
cin>>n;
student stu[n],*ptr;
cout<<"enter data \n";
for (ptr=stu;ptr<(stu+n);++ptr)
{cout<<"name:\n";
gets(ptr->name);
cout<<"roll number:\n";
cin>>ptr->roll_no;}
cout<<"student data:\n";
ptr=stu;
while(ptr<(stu+n))
{ cout<<ptr->name<<" "<<ptr->roll_no<<endl;
ptr++;
}
}
#include<iostream>
#include<string>
usingnamespace std;
struct student
{
string name;
int roll_no;
};
int main()
{
int n;
cout<<"enter number of students that you want to enter their info.\n";
cin>>n;
student stu[n],*ptr;
cout<<"enter data \n";
for (ptr=stu;ptr<(stu+n);++ptr)
{cout<<"name:\n";
getline(cin,ptr->name);
cout<<"roll number:\n";
cin>>ptr->roll_no;}
cout<<"student data:\n";
ptr=stu;
while(ptr<(stu+n))
{ cout<<ptr->name<<" "<<ptr->roll_no<<endl;
ptr++;
}
}
so where did I go wrong in the two codes below?
and is there any other way of doing this right using structures?
*yes it is mandatory*
Your third snippet is closest to being correct. However at line 14 (all snippets) in standard C++, you can not allocate an array like that. In standard C++, the size of an array must be known at compile time. Some compilers do allow this as a non-standard extension.
You also may want to move lines 23-26 outside the for loop if you want to print the roll after all entries have been made.
Line 28: You're missing a close }, but I assume that was just a cut and paste error.