Please help - Lifesaver rating awarded... Can you please explain why the program
ID: 3628400 • Letter: P
Question
Please help - Lifesaver rating awarded...Can you please explain why the program below doesn't compile when using the following operators when both operands are structures:
1) (==) (if (Debra == Jane)
2) (>=) (if (Debra >= Jane)
3) (<=) (if (Debra <= Jane)
How can i fix the code to make it compile. Thanks.
#include <iostream>
#include <string>
using namespace std;
struct student_record
{
string firstname, lastname;
double age, income;
int number_of_children;
char sex;
};
int main()
{
student_record Jane;
student_record Debra;
cout<<"Enter the firstname and lastname: ";
cin>>Jane.firstname;
cin>>Jane.lastname;
cout<<"Enter age: ";
cin>>Jane.age;
cout<<"Enter income: ";
cin>>Jane.income;
cout<<"Enter number of children: ";
cin>>Jane.number_of_children;
cout<<"Enter sex: ";
cin>>Jane.sex;
Debra = Jane;
if (Debra == Jane)
{
cout<<Debra.firstname<<" "<<Jane.lastname<<endl;
cout<<Debra.age<<endl;
cout<<Debra.income<<endl;
cout<<Debra.number_of_children<<endl;
cout<<Debra.sex<<endl;
}
return 0;
}
Explanation / Answer
C++ language does not provide support for equality on structures.
we should do it ourself and compare each structure member by member.
#include <iostream>
#include <string>
using namespace std;
struct student_record
{
string firstname, lastname;
double age, income;
int number_of_children;
char sex;
};
int main()
{
student_record Jane;
student_record Debra;
cout<<"Enter the firstname and lastname: ";
cin>>Jane.firstname;
cin>>Jane.lastname;
cout<<"Enter age: ";
cin>>Jane.age;
cout<<"Enter income: ";
cin>>Jane.income;
cout<<"Enter number of children: ";
cin>>Jane.number_of_children;
cout<<"Enter sex: ";
cin>>Jane.sex;
Debra = Jane;
cout<<Debra.firstname<<" "<<Jane.lastname<<endl;
cout<<Debra.age<<endl;
cout<<Debra.income<<endl;
cout<<Debra.number_of_children<<endl;
cout<<Debra.sex<<endl;
}
return 0;
}