Home > other >  Getting an element of vector which includes enums
Getting an element of vector which includes enums

Time:10-26

I get inputs from user and I put them into a vector. After that I want to get any value of vector at some index. It gives a number. How can I get the exact input value?

enum Enums 
{
    I, O,T, J , L, S, Z
};

int main() 
{


  unsigned int index;
  Piece piece;

 
 
for (index=0; index < 5; index   )  
{
    cout << "What are the " << index 1 << ". piece?\n";
    cin >> piece.inputPiece;
    piece.pieceList.push_back(static_cast<Enums>(piece.inputPiece));
}
 Enums firstPiece= piece.pieceList[0];
 cout <<firstPiece;

}

Out Value is 79;

CodePudding user response:

One way to solve this is to fix the underlying type of the enum to unsigned char and also change the type of inputPiece to unsigned char as shown below:

//----------vvvvvvvvvvvvv---->fixed this to unsigned char
enum Enums: unsigned char 
{
    I, O,T, J , L, S, Z
};

class Piece  
{
public:
//--vvvvvvvvvvvvv------------->changed this to unsigned char
    unsigned char inputPiece;
    vector<Enums> pieceList;    
    
private:
 
};

int main() 
{
  unsigned int index;
  Piece piece;

 
 
for (index=0; index < 5; index   )  
{
    cout << "What are the " << index 1 << ". piece?\n";
    cin >> piece.inputPiece;
    piece.pieceList.push_back(static_cast<Enums>(piece.inputPiece));
}
 Enums firstPiece= piece.pieceList[0]; 
 cout <<firstPiece;//prints I for input I J T L S

}

Working demo.

The output of the program for the input: I J T L S is:

I
  • Related