Skip to main content
GameDev.net gamedev.net
🔒 Locked

Switch Loop with "X" (Optimisation) ?

Started by Merlino Oct 9, 2006 at 3:06 PM 2 replies 850+ views
Original Post
Merlino
Merlino
Hi, i just wanted to know if it is possible to do something with the switch loop: i'm using an example because i can't explain it otherwise ^^; So this is the way I am capable of doing it, but it can be kind of long...

string text;
char imputKeyboardValue
switch (imputKeyboardValue)
{
case 'A':
strcat(text,"A");
break;
case'B':
break;
strcat(text,"B");
break;
case'C':
strcat(text,"C");
break;
}
And so on for Each Signle LeTtEr !! Now here is the more efficient way!! Of course it does not work, but is it possible to do something like this??

string text;
char imputKeyboardValue
switch (imputKeyboardValue)
{
case 'virtualChar':
strcat(text,"virutalChar");
}
ye, it looks kind of strange but I hope you got the idea.. :D Thanks !!!
bakery2k1
bakery2k1
If text is a C++ std::string, you can just write
text += imputKeyboardValue;
If it is a char * string, the type for which you would use strcat, you can still do so but you need to convert your character to a string first, eg:
char tempStr[2] = {imputKeyboardValue, '\0'};strcat(text,tempStr);
Or, you can perform the operations on text yourself:
int textLen = strlen(text);text[textLen] = imputKeyboardValue;text[textLen + 1] = '\0';
Note that in the latter two cases, text had better contain enough storage space for your additional character.
Merlino
Merlino
Ok, kool!!

And what about if I need to convert a char to a class name:
say you have a class named A, another one named B, C and so on..

imagine a program that does: (very simply :D)

char imput;imput->draw();


so the question is "How do I convert a char (or a string) to a variable name, say a name of a class object?" Of course, if it is possible.

Thanks again :D
Fruny
Fruny
Quote:
Original post by Merlino
say you have a class named A, another one named B, C and so on..


If you meant objects, then you can put them up in an array and then do:

array[input]->draw().

If they really are classes, then draw should be a static member function, pointers to which you can put in an array...

Quote:
so the question is "How do I convert a char (or a string) to a variable name, say a name of a class object?" Of course, if it is possible.


In C++, it isn't. You need to build the mapping yourself, or switch to a language that supports reflection (e.g. Python, Java, C#...)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

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

Sign in to reply to this topic.