hello every one.. i m a newbie and was going through structures.the code is as followes:

#include<string>
using namespace std;

#define n_emp 3

struct workerdb {
 string name;
 short age;
 int salary;
}employee[n_emp];

void printdb (workerdb);

int main() {
int n;
for (n=0;n<n_emp;n++) {
 cout<<"name:     "<<endl;
 getline(cin,employee[n].name);
 cout<<endl;
 cout<<"age: "<<endl;
 cin>>employee[n].age;
 cout<<endl;
 cout<<"salary: "<<endl;
 cin>>employee[n].salary;
 cout<<endl;
 }

for (n=0;n<n_emp;n++) {
 printdb (employee[n]);
 }
return 0;
}

void printdb(workerdb employee) {
 cout<<"name:   "<<employee.name<<"\t";
 cout<<"age:    "<<employee.age<<"\t";
 cout<<"salary: "<<employee.salary<<endl;
}

the problem is when i run the program.. for the first structure it asks for the name.. from the next it skips of name input but asks for other field.Thus when the database is complete i gate just the first name but rest structures it remains empty... please run it if i am not clear...

regards
cd-4+

Short answer - don't mix cin and getline.
They don't play well together.
Plenty of past posts and answers for this problem, look around.

Just add

cin.ignore();

at the bottom of your for() loop for input and this will ignore the '\n' character from the last cin.

Also it looks like you do not have

#include <iostream>

at the top of your file for cin and cout usage.

hi .. i m sorry actually while copying i may have missed out.. but that wasn't the problem.. well i don't know if this way is good i found a new way...

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

#define n_emp 3

struct workerdb {
 string name;
 short age;
 int salary;
}employee[n_emp];

void printdb (workerdb);

int main() {
int n;
for (n=0;n<n_emp;n++) {
 cout<<"name:     "<<endl;
 cin>>(employee[n].name);
 cout<<endl;
 cout<<"age: "<<endl;
 cin>>employee[n].age;
 cout<<endl;
 cout<<"salary: "<<endl;
 cin>>employee[n].salary;
 cout<<endl;
 }

for (n=0;n<n_emp;n++) {
 printdb (employee[n]);
 }
return 0;
}

void printdb(workerdb employee) {
 cout<<"name:   "<<employee.name<<"\t";
 cout<<"age:    "<<employee.age<<"\t";
 cout<<"salary: "<<employee.salary<<endl;
}

thanks for your time on this .

regards

The whole reason why you would use the getline() function is to pick up spaces. If I were to input the name "Jim" with just cin, this would work but if I were to give him a last name "Jim McTavish" then it would only take in "Jim" and ignore the space and everything after. With getline() you would get the whole name.

By using cin.ignore() I was able to get it working fine with your code and this adjustment.

.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.