string/char input

Neohacker

Neohacker

@neohacker-FP4O5e Oct 27, 2024
I want to take input for name of a student ...
when i do char name[20]; and take input with cin>>name; it prints only upto 1st space like if i type "jimmy green" then it will print only "jimmy"

when i take string name; and try to input with getline(cin,name) then it prints the next line before the input like this

here is my code :

#include<iostream>
#include<string>
using namespace std;

struct student {
string name;
int age;
};

int main() {
int n;
cout<<"Enter the total no. of students : ";
cin>>n;

student s1[n];

for(int i=0;i<n;i++) {
cout<<"Student "<<i+1<<" : \n\t"<<"Name : ";
getline(cin,s1.name);
cout<<"Age : ";
cin>>s1.age;
}
}


And here is the output :


Enter the total no. of students : 3
Student 1 :
Name : Age :


You see that the "Age" is appearing before entering the "name" ... so how can i fix this problem ??????

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Neohacker

    Neohacker

    @neohacker-FP4O5e Sep 26, 2014

    nvm 😛 i added cin.ignore() after cin and now it's working fine .
  • ManojKiran Eda

    ManojKiran Eda

    @manojkiran-Cse2se Oct 4, 2014

    Another alternative is to use flushall() function after the scanning of an interger.