arrays of structs

Hello, this is my first post so Ill say hi.

Im a complete newbie with C++ and we are learning it at our local college

Im trying to make an array of a struct so I can store name,age and then cout the output in another function.

When I run this program its seems to output a memory address instead of the name i typed in.

here is my code
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

#include <iostream>
#include <string>

using namespace std;


struct customer{
	string name[20];
	int age;
	};

customer inputdetails[10];


void showcustomerdetails(customer inputdetails[])
{
	for (int i=0;i<2;i++)
	{
		cout << inputdetails[i].name << "  " << inputdetails[i].age << endl;
	}
	system("pause");
}

void getcustomerdetails(customer inputdetails[])
{
	for(int i=0;i<2;i++)
	{
	cout << "Please enter customer name: ";
	getline(cin, inputdetails[i].name[19]);

	cout << "Please enter customer age: ";
	cin >> inputdetails[i].age;
	cin.ignore();
	}
}

void main()
{
	getcustomerdetails(inputdetails);
	showcustomerdetails(inputdetails);
}





Please no hard core flamers, Im completely new to this only a few weeks ago.
string name[20];

This is a declaration of an array of 20 strings. You probably just meant:

string name;

As a consequence, when you say:

getline(cin, inputdetails[i].name[19]);

you're writing into the last string in the name array, and when you say:

cout << inputdetails[i].name // ...

you're outputting the value for a pointer to the first element of the name array.
1
2
3
4
struct customer{
	string name[20];
	int age;
	};


In your struct you are declaring variable name as an array of 20 strings. I think what you wanted was string name;. The name of an array, in your example, name, is actually the address of the first element of the array. so in your code:

cout << inputdetails[i].name

it outputs the address.
Thank you so much. Case closed
Topic archived. No new replies allowed.