cin.getline

Am I using cin.getline correctly? building a program using arrays to store data for user inputted employees

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>
#include <istream>
using namespace std;

struct employee
{
	int number;
	char name[20];
	float salary;
};

int main()
{
	employee em[3];

	for (int i = 0; i < 3; i++)
	{
		cout << "Enter employee 3 digit number: " << endl;
		cin >> em[i].number;

		cout << "Enter employee name: " << endl;
		cin.getline(em[i].name[20]);

		cout << "Enter employee salary: " << endl;
		cin >> em[i].salary;

		cout << em[i].number << "" << em[i].name << "" << em[i].salary << endl;
	}
	system("pause");
	return 0;
}
It should be:
 
cin.getline(em[i].name, 20);

you are a life saver thank you very much!!!!
You have a getline just after extracting an int, so you will read the newline left from extracting the int and name will thus be an empty string. You should extract that newline before reading the name.
Topic archived. No new replies allowed.