1

I am trying to solve an assignment and I searched in every possible way for an answer, but managed to only get "how to transform an enum into a string"

I have a string called type that can only contain "webApp", "MobileApp" and "DesktopApp". I have an enum that looks like this:

enum applicationType { webApp = 5, MobileApp = 10, DesktopApp = 15 };

How can I print the value from the enum corresponding to the string using a function?


applicationType print_enum(string tip) {
    //if tip contains "webApp" i should print 5
}

How do I make the function test if the value of the string corresponds to a value in the enum, and if it does print that value?

3
  • Are you certain this is what your assignment asks you to do? It would be a very unhelpful assignment. Your print_enum function seems to return something. There has to be some sort of miscommunication here. Commented Oct 28, 2022 at 1:00
  • @CaptainGiraffe Maybe so, the question was translated between 2 languages and it's possible that I lost the intended meaning of it. Commented Oct 28, 2022 at 1:22
  • Related: stackoverflow.com/questions/28828957/… Commented Oct 30, 2022 at 6:39

1 Answer 1

1

You simply can't.

The names of c++ objects, types and enum entries are not available as strings. They're effectively just placeholders, identifiers for things the compiler needs to identify. It discards these identifiers pretty early on the way from source code to machine code.

(As of c++20. Who knows what the future brings.)

If you need to do that, it's necessary to replicate your enum, e.g. as std::unordered_map<applicationType, std::string>.

If you just need to look up a string based on an integer, just use int instead of an enum type as key in the map, and forget about the enum.

Sign up to request clarification or add additional context in comments.

4 Comments

I understand. That means i misunderstood my assignment given by my professor. I should've posted this too. "2. The function below return a variable of type enum. the function receives one parameter which is a string from the ones above ("aplicatieWeb", "aplicatieMobila", etc) and returns the enum value that corresponds to it."
Can't read that. Edit your question to clarify it.
@Bl4ckSpyrit using a std::unordered_map<std::string, enumType> would easily solve that task.
Yep, exactly. I mean, you've been pointed at std::unordered_map. Maybe check it out on cppreference.com, @Bl4ckSpyrit!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.