Problem with C++ Structures

For a exercise in a book I am using, I have to show a menu on screen, and show stuff from part of a structure depending on what the user picked.

Struct prototype:
1
2
3
4
5
6
7
struct Name 
{
	char fullname[Strsize];		// Name
	char title[Strsize];		// Job title
	char bopname[Strsize];		// BOP name
	int preference;				// 0 = fullname, 1 = title, 2 = BOP name
};


array of that structure:
Name members[MaxMember];

assigning information to structure elements:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
members[0].fullname = "Arthur Bertha";
	members[0].title = "Lead Programmer";
	members[0].bopname = "Big Bertha";
	members[0].preference = 1;

	members[1].fullname = "Cristobal Dolly";
	members[1].title = "Lead Designer";
	members[1].bopname = "Dolly";
	members[1].preference = 2;

	members[2].fullname = "Edouard Fay";
	members[2].title = "Producer";
	members[2].bopname = "Ed";
	members[2].preference = 3;

	members[3].fullname = "Hanna Gustav";
	members[3].title = "Web Developer";
	members[3].bopname = "Hurricane";
	members[3].preference = 1;


When I compile I get many of these errors. this is the one from the members[0].fullname line:
1
2
error C2440: '=' : cannot convert from 'const char [14]' to 'char [40]'
        There is no context in which this conversion is possible
sprintf(members[0].fullname, "%s", "Arthur Bertha");
You're reading the Primer by Prata, aren't you?
Try declaring as an array, maybe (or use Zaita's solution.

Like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Name members[MaxMember] = 
{{"Arthur Bertha",
"Lead Programmer",
"Big Bertha",
1},
{"Cristobal Dolly",
"Lead Designer",
"Dolly",
2},
{
"Edouard Fay",
"Producer",
"Ed",
3,}
{"Hanna Gustav",
"Web Developer",
"Hurricane",
1}
};
If your book has a section on the <cstring> library take a look through it, specifically for strcpy(). There are C++ ways of doing it too, but I don't know whether your book gets that deep.

The "C" way
1
2
3
#include <cstring>
...
strcpy( members[0].fullname, "Arthur Bertha" );

Just keep in mind that strcpy() doesn't check bounds, meaning you must guarantee that the string to copy is no longer than the string to receive.

If you don't want to include <cstring>, then you'll just have to write your own loop:
 
for (const char* s = "Arthur Bertha", char* d = members[0].fullname; (*d = *s); s++, d++);

Yeah, it is ugly, but it'll work.

[edit] wow, I'm slow...
Last edited on
Topic archived. No new replies allowed.