-1

//The class student as two data members, name and roll no. In main function the for loop is used to get the values of data members for each object one by one and then display the name and roll no. of each object. while executing this program it only takes the name of first object and the second object name is skipped and direct the roll no. for second object is asked by the compiler.

include

 using namespace std;
 class student
 {
    string name;
    int roll;
    public:
     void getdata();
    void display();
 };
 void student::getdata()
 {
    cout<<"Enter teh name";
    getline(cin,name);
    cout<<"Enter the roll no";
     cin>>roll; 
 }
 void student::display()
 {
    cout<<name<<"  "<<roll;
    cout<<"\n";
 }
 int main()
 {
    student s[2];
    for(int i=0;i<2;i++)
    {
        s[i].getdata();
        
     }
    for(int j=0;j<2;j++)
    {
        s[j].display();
    }
 
 return 0;
 
 }

//the second object is not taking the string name while executing the program

Community
  • 1
  • 1
Pranay
  • 1

2 Answers2

1

After cin >> roll

add cin.ignore();

Write getdata() as

void student::getdata()
{
cout<<"Enter teh name";
getline(cin,name);
cout<<"Enter the roll no";
cin>>roll; 
cin.ignore();
}
Abdul Rehman
  • 1,687
  • 18
  • 31
0
cin>>roll;
getchar();

When you are giving input for roll.. roll is stored by roll variable. And the enter you pressed is stored by name variable and it is skipped. use getchar() after taking input for roll to take that enter key

Shahriar
  • 13,460
  • 8
  • 78
  • 95