assign a struct variable into another struct variable

I

ineedyourluvin1

Hi, I would appreciate if someone could tell me what
I'm doing wrong ?


#include<iostream>
using namepace std ;

struct person{
char *firstname ;
int age ;
} ;

struct person1{
char *firstname ;
int age ;
} ;

int main(int argc, char *argv[])
{
person me ;
person1 me1 ;

me.firstname = "me" ;
me.age = 150 ;

me1 = me ; // here's where the problem occurrs.....

*The Error Report I Get*

(structs.cpp: in function 'int main()':
structs.cpp:22: error: no match for 'operator=' in 'me1 = me'
structs.cpp:11: error: candidates are: main()::person1&
main()::person1::eek:perator=(const main()::person1&)
structs.cpp:29:1: warning: no newline at end of file
)

Why can't I assign a struct to a struct like i can an int to an int, or
a char to a char, etc ? I can understand it would become
a problem if each struct had different members but these two don't!

thankyou much
 
V

Victor Bazarov

Hi, I would appreciate if someone could tell me what
I'm doing wrong ?


#include<iostream>
using namepace std ;

struct person{
char *firstname ;
int age ;
} ;

struct person1{
char *firstname ;
int age ;
} ;

The two types, 'person' and 'person1' are _distinct_ and _different_
AFA C++ is concerned. It doesn't matter that their internals are the
same. Since you defined two different types, they are different.
int main(int argc, char *argv[])
{
person me ;
person1 me1 ;

me.firstname = "me" ;
me.age = 150 ;

me1 = me ; // here's where the problem occurrs.....

*The Error Report I Get*

(structs.cpp: in function 'int main()':
structs.cpp:22: error: no match for 'operator=' in 'me1 = me'
structs.cpp:11: error: candidates are: main()::person1&
main()::person1::eek:perator=(const main()::person1&)
structs.cpp:29:1: warning: no newline at end of file
)

Why can't I assign a struct to a struct like i can an int to an int, or
a char to a char, etc ? I can understand it would become
a problem if each struct had different members but these two don't!

You need to define (overload) the assignment operator for 'person' to
allow assigning from a 'person1' value. Read about operator overloading
in your favourite C++ book.

V
 
J

Jonathan Mcdougall

Hi, I would appreciate if someone could tell me what
I'm doing wrong ?


#include<iostream>
using namepace std ;

struct person{
char *firstname ;
int age ;
} ;

struct person1{
char *firstname ;
int age ;
} ;

int main(int argc, char *argv[])
{
person me ;
person1 me1 ;

me.firstname = "me" ;
me.age = 150 ;

me1 = me ; // here's where the problem occurrs.....

*The Error Report I Get*

(structs.cpp: in function 'int main()':
structs.cpp:22: error: no match for 'operator=' in 'me1 = me'
structs.cpp:11: error: candidates are: main()::person1&
main()::person1::eek:perator=(const main()::person1&)
structs.cpp:29:1: warning: no newline at end of file
)

Why can't I assign a struct to a struct like i can an int to an int, or
a char to a char, etc ? I can understand it would become
a problem if each struct had different members but these two don't!

Doesn't matter. These two structs are different because of their names.
Even if their members are identical, they are still apples and bananas
to the compiler.


Jonathan
 
L

leonardo77

*The Error Report I Get*

(structs.cpp: in function 'int main()':
structs.cpp:22: error: no match for 'operator=' in 'me1 = me'
structs.cpp:11: error: candidates are: main()::person1&
main()::person1::eek:perator=(const main()::person1&)
That's the important error.
Why can't I assign a struct to a struct like i can an int to an int, or
a char to a char, etc ? I can understand it would become
a problem if each struct had different members but these two don't!

The problem is the same as trying to assign two variables of
incompatible types.Even though the variables have an identical layout,
the variable have different types.It's like trying to assign a 'float*'
to an 'int*'.They possibly have similar layout,but different meanings.A
person1 isn't a person,although they have the same members.

Hope I was helpful.
 
I

ineedyourluvin1

Could you give me a brief discription of
overloading the assignment operator ?
You've all been so helpful! :)
 
V

Victor Bazarov

Could you give me a brief discription of
overloading the assignment operator ?
You've all been so helpful! :)

struct B;
struct A {
A& operator=(B const&);
};

struct B { };

A& A::eek:perator =(B const& b)
{
// do what you need to copy stuff from 'b' to '*this'
return *this;
}

int main() {
A a;
B b;
a = b;
}

V
 
I

ineedyourluvin1

struct B;
struct A {
A& operator=(B const&);
};

struct B { };


A& A::eek:perator =(B const& b)
{
// do what you need to copy stuff from 'b' to '*this'
return *this;
}


int main() {
A a;
B b;
a = b;
}


V


This is great! Thanks so much! I'll study how you did that code snippet
second thing when I get up
tomorrow. I'll also look up operator overloading. Hey, u think we could
discuss loading an ascii text
file into a struct like say, struct phonebook{} ? That would be great,
I've always wanted to be able to do that and it would further my C++
career! You guys/gals have been great!
 
V

verec

Hi, I would appreciate if someone could tell me what
I'm doing wrong ?
#include<iostream>
using namepace std ;

struct person{
char *firstname ;
int age ;
} ;
struct person1{
char *firstname ;
int age ;
} ;

int main(int argc, char *argv[])
{
person me ;
person1 me1 ;

me.firstname = "me" ;
me.age = 150 ;

me1 = me ; // here's where the problem occurrs.....

The other posters have very valid points, but just two things:

If what you wrote, really, is what you meant, then you can
solve this "the old way" :

* (person *) &me1 = me ;

or using modern syntax:

* static_cast<person *>(&me1) = me ;

The second thing is, did you really mean you wrote?
What's the purpose of defining two different structs
which are otherwise identical as to their members?

My take is what you need really is:

struct person {
char * name ;
int age ;
} ;

int main() {
person me ;
person me1 ;

me.name = "me" ;
me.age = 15 ;

me1 = me ;
}
 
I

ineedyourluvin1

Thanks JFB and again to everyone else who helped
me with this . I just got out of bed and was having dreams about
programming! That happens when I program right before I go to bed.
Since this has all sunk in now, I'm going to have to find a way to read
a text file into a struct because
I'm working on another program which requires it.
An example of that would be load people.dat
into struct person. I tried this, since you can do struct person me =
{"me",150}, I had the same
format in my text file. Comma separated values.
It gave me errors ... Think anyone could help with that issue as well ?
I love comp.lang.c++ !
thanks again!
 
K

Karl Heinz Buchegger

Thanks JFB and again to everyone else who helped
me with this . I just got out of bed and was having dreams about
programming! That happens when I program right before I go to bed.
Since this has all sunk in now, I'm going to have to find a way to read
a text file into a struct because
I'm working on another program which requires it.
An example of that would be load people.dat
into struct person. I tried this, since you can do struct person me =
{"me",150}, I had the same
format in my text file. Comma separated values.
It gave me errors ... Think anyone could help with that issue as well ?
I love comp.lang.c++ !
thanks again!

What exactly are your errors and what exactly does your program look like?
Just the part of the programming which deals with reading from file
would be enough. But make sure, that the thing you post is by itself
a complete program. That is: We can cut&paste it into our development
environments, compile it and see the same errors as you do (no missing
data types, no missing function declarations).
 
I

ineedyourluvin1

Ok Karl, here the code . It compiles with no errors and 1 warning in
MSVC 6.0 but when I run it I get
the Windows message, "Program.exe has encountered an error and needs to
close."
The warning was about the instance of person, me,
not being initialized.

The code:

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


struct person
{
char *name ;
char *age ;
} ;


int main()
{
person me ;
char str[2000];
fstream file_op("person.txt",ios::in);
while(!file_op.eof())
{
file_op.getline(str,2000);
person me = {str} ;
}
file_op.close();

cout << me.age << " " << me.name << endl ;

return 0 ;

}
 
K

Karl Heinz Buchegger

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

struct person
{
char *name ;
char *age ;
} ;

int main()
{
person me ;
char str[2000];
fstream file_op("person.txt",ios::in);
while(!file_op.eof())
{
file_op.getline(str,2000);

at this line you have the content of a single input line available.
Now it is up to you to seperate the individual parts of the input
line into name and age.
person me = {str} ;

That declares a fresh new variable called me and initializes it with str.
Note: This me is *not* identical to the me at the outermost level. It is
a fresh new variable. It comes into existence in this line and goes out
of scope with the '}' in the next line
}
file_op.close();

cout << me.age << " " << me.name << endl ;

me.age has never been given a value, thus this pointer here points
into nomansland. Same for me.name.


I leave it up to you to figure out a way to strip the individual parts
out of the read input line.
But what comes next? You need to store those parts in 'me'. And this
is how to do it:

while( file.getline( str, 2000) {
// filter out the 'name' and 'age'
// from str and store them in 2 seperate
// variables
char name[1000] = {0};
char age[1000] = {0};

// now here is your code to extract name and age from str
// this code is left as an exercise to the reader

// and here the assignment to 'me' takes place
me.name = new char[ strlen( name ) + 1 ];
strcpy( me.name, name );

me.age = new char[ strlen( name ) + 1 ];
strcpy( me.age, age );
}

if( !file_op.eof() ) {
cout << "Something went wrong during reading the file" << endl;
return EXIT_FAILURE;
}

file_op.close();

cout << me.age << " " << me.name << endl;

delete [] me.age;
delete [] me.name;

return EXIT_SUCCESS;
}


But all of this begs the question: Why do you use those error prone
character arrays at all? Using std::string would be so much simpler.

Also note: Your usage of foef() was wrong! In the above I showed how
to use it. foef() gets true only after you tried *and* failed to read
from a file.
 
I

ineedyourluvin1

Do you mean I can completely not use
char arrays and use strings in its place ?
That would be great. I know string is a
class so would be usefull either way.
So instead of char *name , or char name[] = "me",
etc. I can just do string name, or string name = "me" all the time ? I
know it's possible to do
string primarykey[100] , etc, etc. As far as
the file.eof(), I'm still learning file i/o. It's hard but
I love c++ and am willing to become the master
programmer :) thanks lots! I'd love to continue
discussion and in the meantime im going to practice on the code you
just posted Karl.
 
K

Karl Heinz Buchegger

Do you mean I can completely not use
char arrays and use strings in its place ?

What books on C++ are you reading?
They don't seem to be very good.
 
I

ineedyourluvin1

i just found a great way to read and write structs to and from a file.

CODE:

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

#define FILE_IN "datafile.txt"

struct Person {
char name[50] ;
int age ;
char sex ;
} ;

int main()
{
Person People ;
strcpy(people.name, "Me") ;
people.age = 150 ;
people.sex = 'F' ;

cout << "\n Our person is " << people.name ;
cout << "\n His/Her sex is " << people.sex ;
cout << "\n His/Her age is " << people.age ;

// set up streams for output

ofstream output ; // output stream object
output.open(FILE_OUT, ios::eek:ut | ios:binary) ;
output.write((char *) &people, sizeof(Person)) ;

cout << "\n All done writing our person to the file!"\n" ;

output.close() ;

// Now we will read the person from file into a new person object
created from the struct!

Person newperson ;

ifstream input ;

input.open(FILE_IN, ios::eek:ut | ios::binary) ;
if(!input){
cout << "Can't find input file " << FILE_IN << " !" ;
exit(1) ;
}

input.read((char *) &newperson, sizeof(Person)) ;

cout << "\n The new person is " << newperson.name ;
cout << "\n His/Her sex is " << newperson.sex ;
cout << "\n His/Her age is " << newperson.age ;

input.close

return 0 ;
}
 
K

Karl Heinz Buchegger

i just found a great way to read and write structs to and from a file.

[snip code demonstrating that the OP found out about binary files and
the read, write calls]

But be carefull. This works only with structs containing no pointers
and no virtual functions. Another drawback is that you have tied your
program to not only your computing environment but also to your compiler.
As soon as you switch to a different compiler, your program may or
may not be able to read old data files.

Also: Version management of different data file versions becomes a nightmare.
 
I

ineedyourluvin1

Yeah that would be right because when I
do input.read((char *) &newperson, sizeof(Person)) ; , or the output ,
the sizes of
some datatypes may be different. Thus,
the file on the disk wont match anymore.
Right ? And as far as the pointers are concerned,
they are used to point to a location in memory
which will change all the time therefore
useless and troublesome in this type of
application.
 
K

Karl Heinz Buchegger

Yeah that would be right because when I
do input.read((char *) &newperson, sizeof(Person)) ; , or the output ,
the sizes of
some datatypes may be different. Thus,
the file on the disk wont match anymore.
Right ?

Only if you change the layout of that struct, eg. by
introducing new data members or deleting some or resizing
character arrays to different lengths, etc. All in all something
that is done sometimes.
And as far as the pointers are concerned,
they are used to point to a location in memory
which will change all the time therefore
useless and troublesome in this type of
application.

I am impressed. Most people don't grasp this that fast.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top