Skip to main content
gamedev.net
🔒 Locked

Calling a variable with a string

Started by Skiller Mar 12, 2003 at 11:04 PM 4 replies 200+ views
Original Post
Skiller
Skiller
Hi, i''m new to c and would like to know if it is possible to use a string to call a variable without using a series of if statements. It''s hard to explain but what i want to do is have my game read a variable name from a txt file and then use it in the program. Please let me know if it is/isn''t possible and how it''s done (if it is). Thanks -Skiller
-Skiller
kuphryn
kuphryn
No. There are more elegant solutions using C++ such as a map, but not C.

Kuphryn
Skiller
Skiller
I think i am using c++ so could u explain how its done in that

-Skiller
-Skiller
Zipster
Zipster
What you''d want is an std::map to map a std::string to a function pointer. You can do it ye'' old fashioned way:
typedef void (*VOIDFUNC)(void);
std::map< std::string, VOIDFUNC > MyMap;

void Foo(void)
{
std::cout << "FOO!";
}

// Add it
MyMap["Foo"] = Foo;

// Call it (I think this is correct)
MyMap["Foo"]();


...or wait for Fruny to show up and give you the pure C++ way with all the fancy template structure function pointer doohickeys!
Skiller
Skiller
Sweet, that exactly the kind of thing i was hopin existed, thanks

-Skiller
-Skiller

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.