I noticed that using a switch statement, the case always has to be a constant character or integer or it won't compile. It's sorta of a bummer as the only alternative is using a bunch of if/else if's.

So doing something like this won't work:

switch(aString)
{
               case "word1": doSomething(); break;
               case "word2": doSomething(); break;
               case "word3": doSomething(); break;
}

or even something like this won't work.

switch(aString)
{
               case strToNum("word1"): doSomething(); break;
               case strToNum("word2"): doSomething(); break;
               case strToNum("word3"): doSomething(); break;
}

So is there any intutive way of going around this? I think I found somewhere you can use enums but thats all I could find.

You can create an std::map, that maps the strings to integral values. Then call map::find and use the returned iterator to retrieve the key and use that in the switch switch statement.

On the same lines you could have a map that maps strings to function pointers. Provided you can have all functions to have the same signature (or if you can create delegate functions which have the same signature and internally call the respective functions) and then can directly call the function based on the input string.

Example:

#include <iostream>
#include <map>
#include <string>

typedef void(*pf)();
typedef std::map<std::string,pf> FnMap;

void letsWork(const std::string& work, FnMap* fnMap);
void work1(){	std::cout << "work1" << std::endl;}
void work2(){	std::cout << "work2" << std::endl;}

int main()
{
	FnMap* fnMap = new FnMap();
	
	std::string _work1 = "work1";
	std::string _work2 = "work2";

	fnMap->insert(std::pair<std::string,pf>(_work1,work1));
	fnMap->insert(std::pair<std::string,pf>(_work2,work2));

	std::string work;
	std::cout << "What work?" << std::endl;
	std::cin >> work;

	letsWork(work,fnMap);
	
	std::cin.ignore();
	std::cin.get();
	
	delete fnMap;
}

void letsWork(const std::string& work, FnMap* fnMap){
	if(fnMap->count(work) > 0) (fnMap->find(work))->second();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.