Haik Hakopyan
Haik Hakopyan

Reputation: 15

Using enum with rand() function

Noob programmer here, trying to get some help on a assignment. I will use a similar example, if someone can help me figure out what I am doing wrong that would be great. I am aware rand is a integer and it cannot be set equal to enum by default. I am trying to get rand integer to pair a randomly selected enum. Sorry for reposting a question already asked, but other examples written by other users kinda confuse me.

NOTE: I did not add srand to seed random number because in my specific assignment, it does not need to be seeded according to my instructor, not sure why but just following instructions.

#include <iostream>
#include <ctime>
#include <iomanip>

using namespace std;

int main(){ 

  enum SHIRT_COLOR { WHITE, BLACK, RED, GREEN};
  int value = 0; //rand num to be generated
  value = rand() % 4;

  SHIRT_COLOR shirt = WHITE;
  SHIRT_COLOR shirt = BLACK;
  SHIRT_COLOR shirt = RED;
  SHIRT_COLOR shirt = GREEN;
  shirt = static_cast<SHIRT_COLOR>(value);

  cout << "Random Shirt Color: " << shirt;

}    

Upvotes: 0

Views: 155

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

There are two problems here, but neither of them have anything to do with rand().


Multiple declarations

  SHIRT_COLOR shirt = WHITE;
  SHIRT_COLOR shirt = BLACK;
  SHIRT_COLOR shirt = RED;
  SHIRT_COLOR shirt = GREEN;

Here you create four variables with the same name. It's not clear why you do this.

Just make one variable for the shirt colour you've chosen:

  SHIRT_COLOR shirt = static_cast<SHIRT_COLOR>(value);

Output

C++ doesn't know how to print your enums, out of the box, and your program doesn't know about these variable/constant names; they only exist in your source code.

Presumably, then, you are receiving a compilation error on this line:

cout << "Random Shirt Color: " << shirt;

You'll need to sort this yourself, either with a std::map, or a switch, or even just a series of if/else if given the scale involved.


Other than that, your approach is fine.

The static_cast makes sense.

Regarding srand(), fair enough if you have to omit it to pass your assignment, but your instructor is wrong to claim that it should not be in there.

Furthermore, in production code in the future you shall be using the C++11 random features, not ancient rand(). 😀 You'll probably never be taught that in school, because schools do not teach production-quality C++, but it is something you should look into yourself either now or when you hit the jobs market.

Upvotes: 2

Related Questions