enum and value-returning.

So I kind of understand bits and pieces of this and I have some of it done but I don't have all of it and I want to make sure that I'm not doing it completely wrong. So if someone could do these so I can check mine against it and any explanation as to what and why you did it would be greatly appreciated. Thanks :D

1. Declare an enumeration type consisting of the nine planets in their order by distance from the Sun (Mercury first, Pluto last).
2. Write a value-returning function that converts the name of a planet given as a string parameter to a value of the enumeration type declared in Exercise 1. If the string isn't a proper planet name, return "EARTH".
3. Write a value-returning function that converts a planet of the enumeration type declared in Exercise 1 into the corresponding string. The planet is an input parameter and the string is returned by the function. If the input is not a valid planet, return "Error".
4. Write a For Statement that prints out the names of the planets in order, using the enumeration type declared in Exercise 1 and the function declared in Exercise 3.

For number 1 I put:
enum Planet {MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO};
That's the only one that I think I'm totally solid on.
There is no easy way to convert from enum to string so you will need to look up a switch statement and use it to manually convert each enum to a string.

Every switch should have it's cases and you will use the enum as cases.
Can you return a string in a value-returning function?
You can return a std::string
Just so you know, Pluto is no longer a planet. lol.

http://news.nationalgeographic.com/news/2006/08/060824-pluto-planet.html
A more efficient way to convert a continuous series of integers to any other type is to use a look-up table:

1
2
3
4
5
string toString(Planet planet)
{
	static string lookup[] = { "Mercury", "Venus", /*...*/, "Neptune" }
	return lookup[planet];
}

So, instead of O(n), you get O(1) (simple pointer addition).
Topic archived. No new replies allowed.