0

In a program I created I need to get some customer information to an array. Below are the codes regarding my question.

struct CustomerType
{
    string fName;
    string lName;
    char gender;
    string address;
    string contactNo;
};

CustomerType Customer[1000];

I have the following code to get the input from user. Here i is the index of the customer I'm getting information about.

string add="";
cout<<left<<"\n"<<setw(29)<<"\t\t Name"<<": ";
    cin>>Customer[i].fName>>Customer[i].lName;
cout<<left<<"\n"<<setw(29)<<"\t\t Gender"<<": ";
    cin>>Customer[i].gender;
cout<<left<<"\n"<<setw(29)<<"\t\t Address"<<": ";
    getline(cin,add); Customer[i].address=add;
cout<<left<<"\n"<<setw(29)<<"\t\t Contact No."<<": ";
    cin>>Customer[i].contactNo;

But when I run the program, it only asks to input the name, gender and contact no. but not the address. It works like there is no getline command.

How do I fix this?

Dishon Michael
  • 157
  • 1
  • 2
  • 6

2 Answers2

1

This is the old problem if "getline doens't skip newline in the input, but operator >> does" problem. Simple solutions include:

  1. Use a cin.ignore(1000, '\n'); to skip over the next newline (assuming less than 1000 characters before the newline). This line goes before the getline call.
  2. Use only getline to read data in general, and then use other methods to read out the actual content. [In your case, the only one that is somewhat difficult is the gender member variable - but you probably want to deal with someone writing "Female" and then address becomes "emale" in some way anyway, so may not be a big issue.
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

You need to flush the buffer after using cin if your using getline after it. If you don't do that, the getline command will try to read the buffer and get the "endline" thats left from the cin and use that for its input automatically.

You can do that simply by putting cin.ignore(); before the getline(); Or use fflush(stdin) like you'd use in C.

Gust Jc
  • 181
  • 1
  • 2