getline??

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
clrscr();
int age;
char name[20],c[20],gen[20];
ofstream yo("Yo.txt");
cout<<"Enter name ";
cin.getline(name,20);
cout<<"Enter age ";
cin>>age;
cout<<"Enter gender ";
cin.getline(gen,20);
cout<<"Nationality ";
cin.getline(c,20);
yo<<"Name : "<<name<<endl;
yo<<"Age : "<<age<<endl;
yo<<"Gender : "<<gen<<endl;
yo<<"Nationality: "<<c<<endl;
getch();
}



I am beginner at C++ and we are using Turbo c++.
So the problem is gender input is not working, it directly skips to nationality.
The problem is that you are using getline after a >> operator. The >> operator reads everything up to a newline operator leaving the newline operator in the stream. When you call the getline function, it reads in only the newline(\n) operator that was left in the stream. You have to take care of the newline operator by ignoring it or storing it into a variable that you won't be using.

Something like cin.ignore() before you ask for the gender in order for it to ignore the newline operator.

Or creating a string called remainder and calling getline(cin, remainder) before you ask for gender that way it will store the newline operator into that remainder variable.
Topic archived. No new replies allowed.