I am new to c++ , I was trying to print the fields of a structure using an array.
I know the compiler is not able to understand what is inside deck[1] in the line for(int x:deck[1])
, since deck[1] is an unknown data type (a structure datatype defined as 'card'). So x is not able to scan the elements within this data type.
I wish to know, how may I print the elements within this deck[1], i.e {1,1,1}.
#include <iostream>
using namespace std;
struct card
{
int face;
int shape;
int color;
};
int main()
{
struct card deck[52];
deck[1].face=1;
deck[1].shape=1;
deck[1].color=1;
cout<< sizeof(deck)<<endl;
for(int x:deck[1])
{
cout<<x<<endl
}
return 0;
}
Note that you can't loop through the data members of an object of a class type such as card
. You can only print out the data members individually. So you can use operator overloading to achieve the desired effect. In particular, you can overload operator<<
as shown below.
#include <iostream>
struct card
{
int face;
int shape;
int color;
//overload operator<<
friend std::ostream& operator<<(std::ostream &os, const card& obj);
};
std::ostream& operator<<(std::ostream &os, const card& obj)
{
os << obj.face << " " << obj.shape << " " << obj.color;
return os;
}
int main()
{
card deck[52] = {};
deck[1].face = 1;
deck[1].shape = 1;
deck[1].color = 1;
std::cout << deck[1].face << " " << deck[1].shape << " " << deck[1].color << std::endl;
//use overloaded operator<<
std::cout << deck[1] << std::endl;\
}
The output of the above program can be seen here:
1 1 1
1 1 1