1

So I'm trying to make a program that asks a user for a planet, this is stored as a string. I want to use a switch statement to make decisions (like if it's earth do this, if it's mars do this). I am aware that switch statements only take ints, so I took the string and translated it to its hex value. The issue I'm stuck on is how do I have the hex value saved as an int.

I am aware that it would be way easier to do a bunch of nested if statements, but I find that really ugly and bulky.

Here is what I have so far:

/*
 * Have user input their weight and a planet
 * then output how heavy they would be on that planet
 * if planet is wrong
 * output it
*/

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string returnanswer(string x) {
    string dat = x;
    int test;
    ostringstream os;

    for (int i = 0; i < dat.length(); i++)
        os << hex << uppercase << (int) dat[i];

    string hexdat = os.str();

    cout << "Text: " << dat << endl;;
    cout << "Hex: " << hexdat << endl;

    return hexdat;
}

int main() {
    int weight;
    string planet;

    cout << "Please enter your weight: " << endl;
    cin >> weight;
    cout << "Please enter Planet" << endl;
    cin >> planet;

    returnanswer(planet);
    return 0;
}
pgngp
  • 1,552
  • 5
  • 16
  • 26
JFC
  • 13
  • 5
  • Don't apply complex conversions so you can use a specific control structure. Use some `if` statements. Sometimes a dispatch dictionary is appropriate (i.e. `std::map>` but that would probably be overkill for the planets in the solar system) – Aluan Haddad Feb 07 '18 at 03:06
  • ok, so I should just do a bunch of if statements? – JFC Feb 07 '18 at 03:13
  • 1
    ^ I think the mapping of strings to actions would be best, however if you want to stay on this route consider [`std::hash`](http://en.cppreference.com/w/cpp/utility/hash) – kmdreko Feb 07 '18 at 03:23
  • Use a `std::unordered_map` to map uppercase planet names to integer id's. – Cheers and hth. - Alf Feb 07 '18 at 03:41

1 Answers1

0

One way to convert a string hex to an int (using the suggestion from C++ convert hex string to signed integer) would be this:

unsigned int num;
stringstream ss;
ss << hex << hexdat;
ss >> num;

num would now contain the int value of hexdat.


On a side note, instead of converting the planet name to a hex and then to a string, you should consider using an unordered_map (as others have suggested), for example unordered_map<string, Enum> that maps user input planet names to Enum values. The planet Enum would look something like this:

enum Planet {mercury, venus, earth, mars, jupiter, saturn, uranus, neptune};
pgngp
  • 1,552
  • 5
  • 16
  • 26