Sign in to follow this  
Merlino

Switch Loop with "X" (Optimisation) ?

Recommended Posts

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 !!!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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#...)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this