1 2 3 4 5 6
|
for(int i=0; i<x; i++)
{
cout<<"Enter details for student "<<i+1<<".\n";
cout<<"Enter student name: "; getline(cin,student[x].name); // change to student[i]
cout<<"\nEnter marks: "; cin>>student[x].marks; // change to student[i]
}
|
You want to loop on i, not x.
Edit: And you'll have to use
cin.ignore();
Read here why -
http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include<string> // #include <string> not <string.h>
using namespace std;
struct st
{
string name;
long marks;
};
int main()
{
int x;
cout<<"Enter no. of students.\n";
cin>>x;
st* student=new st[x];
for(int i=0; i<x; i++)
{
cin.ignore();
cout<<"Enter details for student "<<i+1<<".\n";
cout<<"Enter student name: "; getline(cin,student[i].name);
cout<<"\nEnter marks: "; cin>>student[i].marks;
}
delete[] student;
}
|
Last edited on
Yeah what Tarik said
You are inputting [x] as the index every time so you are effectively rewriting [x] index x times
You also need to put cin.ignore(); right before your getline to clear the return flag (i think that's the right explanation)