Sinisterly
"Switch" with string? - Printable Version

+- Sinisterly (https://sinister.ly)
+-- Forum: Coding (https://sinister.ly/Forum-Coding)
+--- Forum: C, C++, & Obj-C (https://sinister.ly/Forum-C-C-Obj-C)
+--- Thread: "Switch" with string? (/Thread-Switch-with-string)

Pages: 1 2


"Switch" with string? - Diabolic666 - 11-26-2011

Hey guys,

As I've posted yesterday, I'm doing a random program and I wanted to implement windows cmd prompt in it.

I was thinking on using the C++ program and calling the "system()" for the command depending on the user input, but turns out, you can't use the "switch" with strings Tongue

My other idea was to run cmd.exe? I don't really know :wacko:

What do you suggest?


RE: "Switch" with string? - puma - 11-26-2011

What's your question, because what you posted seemed more like a comment than a question...

If you're wanting to switch based on user input you can read it into a string and then compare it to an expected value and execute what you want.

For example

if ((userInput.Compare("something") == 0)) {
system("something here");
} else if ((userInput.Compare("something else") == 0)) {
system("something else here");
}



RE: "Switch" with string? - Diabolic666 - 11-26-2011

(11-26-2011, 11:13 PM)puma Wrote: What's your question, because what you posted seemed more like a comment than a question...

If you're wanting to switch based on user input you can read it into a string and then compare it to an expected value and execute what you want.

For example

if ((userInput.Compare("something") == 0)) {
system("something here");
} else if ((userInput.Compare("something else") == 0)) {
system("something else here");
}

I wanted to know if I could do like this:

Code:
string x;

switch (x)

    case "sometext":
    {...}

But I've found a better way to do what I wanted:

Code:
cin >> input;
cin.get();
system(input);

Simple as that, although I would still want to know if I could do what I indicated Tongue


RE: "Switch" with string? - puma - 11-27-2011

(11-26-2011, 11:24 PM)Diabolic666 Wrote: I wanted to know if I could do like this:

Code:
string x;

switch (x)

    case "sometext":
    {...}

But I've found a better way to do what I wanted:

Code:
cin >> input;
cin.get();
system(input);

Simple as that, although I would still want to know if I could do what I indicated Tongue

No, you can't switch on a string in c++. The only way to do it is with if statments and compare Sad



RE: "Switch" with string? - Diabolic666 - 11-27-2011

(11-27-2011, 10:57 PM)puma Wrote: No, you can't switch on a string in c++. The only way to do it is with if statments and compare Sad

That sucks :c


RE: - Frooxius - 11-29-2011

C/C++ doesn't even support string datatype natively. What it uses are basically arrays of datatype char, terminated with a null character (basically equal to zero). In case of C++, there's a String class in the STL library, which is part of C++ standard, this is however still a library, therefore can't be mixed with the language construct themselves like that.

Keep in mind, that C/C++ are very close to machine language, they are more low level languages than other languages you may now, so they provide less level of abstraction - meaning what some language can do for you (like switch with a string), you have to do it for yourself, as it's something that can't be done directly on the most contemporary hardware.

C/C++ switch needs to be used with a number, which the processor can work with directly. So if you have for example this:

Code:
switch(a)
{
case 3:
   ...
   break;
case 8:
   ...
   break;
default:
  ...
}

It will get translated into something like this:

Code:
CMP 3, [a]
JNE case_8
...
JMP end_switch
case_8:
CMP 8, [a]
JNE case_default
...
JMP end_switch
case_default:
...
end_switch:

Notice the CMP (compare) instructions, that work with numbers. They can't work with a string, because even the most simple type of string is an array of arbitrary size in the memory and I can't remember any specific processor that could work with them natively.

So what is needed to do, is to somehow convert the string to a number. This can be done in C/C++ as following:

The Solution

You basically need to make an list of strings that you expect and make an enumeration with appropriate names for expected strings. Then define a function, that will translate the input string into the number, that corresponds with your enumeration - enumeration names correspond to a integer number, so they can be used with a switch.

This is a working C++ example, using standard C++. If you have any further questions, asks, feel free to alter it to suit your needs and use in any projects.
Code:
#include <iostream>
#include <istream>
using namespace std;

// List if strings you want to decode, in textual form
char *input_strings[] =
{
    "COPY",
    "MOVE",
    "BURP",
    "HUG",
    "GLOMP",
    "EXIT"
};

// List of corresponding names for strings you want to decode, MUST match intput_strings
enum decoded_string
{
    strCOPY,
    strMOVE,
    strBURP,
    strHUG,
    strGLOMP,
    strEXIT,

    strTERMINATOR    // MANDATORY! Must be always at the end of the list and must be always there
};

// decode function - goes trough input_strings and matches it to the input string
decoded_string DecodeString(char *input_string)
{
    int i;
    for(i = 0; i < strTERMINATOR; ++i)
        if(!strcmp(input_string, input_strings[i]))
            break;

    return (decoded_string)i;
}

int main()
{
    char input[256];
    // infinite loop, not the best solution but... ah well :P
    for(;;)
    {
        cout << "Enter command: ";
        cin.getline(input, 256);    // get the user input

        // Tamtadadada! Using string with switch? Miracles? Nah, just Frooxius was here x3
        switch( DecodeString(input) )
        {
        case strCOPY:
            cout << "Copy what? Where?! I'm confused AAAAARGH\n";
            break;

        case strMOVE:
            cout << "No. YOU move.\n";
            break;

        case strBURP:
            cout << "Ewww, that's disgusting :-/\n";
            break;

        case strHUG:
            cout << "YAAAAY! Hugs! ^^\n";
            break;

        case strGLOMP:
            cout << "*glomps the user*\n";
            break;

        case strEXIT:
            cout << "BYEEEEE\n";
            return 0;

        default:
            cout << "I'm not sure what you mean by that...\n";
            break;
        }
    }
}



RE: - Diabolic666 - 11-29-2011

(11-29-2011, 11:46 AM)Frooxius Wrote: C/C++ doesn't even support string datatype natively. What it uses are basically arrays of datatype char, terminated with a null character (basically equal to zero). In case of C++, there's a String class in the STL library, which is part of C++ standard, this is however still a library, therefore can't be mixed with the language construct themselves like that.

Keep in mind, that C/C++ are very close to machine language, they are more low level languages than other languages you may now, so they provide less level of abstraction - meaning what some language can do for you (like switch with a string), you have to do it for yourself, as it's something that can't be done directly on the most contemporary hardware.

C/C++ switch needs to be used with a number, which the processor can work with directly. So if you have for example this:

Code:
switch(a)
{
case 3:
   ...
   break;
case 8:
   ...
   break;
default:
  ...
}

It will get translated into something like this:

Code:
CMP 3, [a]
JNE case_8
...
JMP end_switch
case_8:
CMP 8, [a]
JNE case_default
...
JMP end_switch
case_default:
...
end_switch:

Notice the CMP (compare) instructions, that work with numbers. They can't work with a string, because even the most simple type of string is an array of arbitrary size in the memory and I can't remember any specific processor that could work with them natively.

So what is needed to do, is to somehow convert the string to a number. This can be done in C/C++ as following:

The Solution

You basically need to make an list of strings that you expect and make an enumeration with appropriate names for expected strings. Then define a function, that will translate the input string into the number, that corresponds with your enumeration - enumeration names correspond to a integer number, so they can be used with a switch.

This is a working C++ example, using standard C++. If you have any further questions, asks, feel free to alter it to suit your needs and use in any projects.
Code:
#include <iostream>
#include <istream>
using namespace std;

// List if strings you want to decode, in textual form
char *input_strings[] =
{
    "COPY",
    "MOVE",
    "BURP",
    "HUG",
    "GLOMP",
    "EXIT"
};

// List of corresponding names for strings you want to decode, MUST match intput_strings
enum decoded_string
{
    strCOPY,
    strMOVE,
    strBURP,
    strHUG,
    strGLOMP,
    strEXIT,

    strTERMINATOR    // MANDATORY! Must be always at the end of the list and must be always there
};

// decode function - goes trough input_strings and matches it to the input string
decoded_string DecodeString(char *input_string)
{
    int i;
    for(i = 0; i < strTERMINATOR; ++i)
        if(!strcmp(input_string, input_strings[i]))
            break;

    return (decoded_string)i;
}

int main()
{
    char input[256];
    // infinite loop, not the best solution but... ah well :P
    for(;;)
    {
        cout << "Enter command: ";
        cin.getline(input, 256);    // get the user input

        // Tamtadadada! Using string with switch? Miracles? Nah, just Frooxius was here x3
        switch( DecodeString(input) )
        {
        case strCOPY:
            cout << "Copy what? Where?! I'm confused AAAAARGH\n";
            break;

        case strMOVE:
            cout << "No. YOU move.\n";
            break;

        case strBURP:
            cout << "Ewww, that's disgusting :-/\n";
            break;

        case strHUG:
            cout << "YAAAAY! Hugs! ^^\n";
            break;

        case strGLOMP:
            cout << "*glomps the user*\n";
            break;

        case strEXIT:
            cout << "BYEEEEE\n";
            return 0;

        default:
            cout << "I'm not sure what you mean by that...\n";
            break;
        }
    }
}

Once again, thank you for your help!

I had quite forgotten that processors use numbers, not characters, to operate :epic:

Although I already found a solution, if I ever need a switch with a string, this is going to work perfectly, so thank you once more for your help and patience Smile


RE: "Switch" with string? - Frooxius - 11-30-2011

Glad to help (though a small pointer: you don't need to quote my whole post, especially if it's very long).

Also, in computing, characters basically ARE numbers, there's just some character assigned to some of the numbers using some stable, usually the ASCII for basic set (and in standard C/C++) or UTF-8 for example if you want to make it more multinational.

What solution did you find?


RE: "Switch" with string? - Diabolic666 - 12-01-2011

I just took the input from the user and used it in the system() directly, like:

Code:
cin >> input;
    cin.get();
    system(input);

But the method wasn't doing what I really wanted to do, having cmd prompt running on the application.

What I mean by that was that I had the app that served as a calculator, an char to int, and vice-versa, converter and a command prompt (running within the command prompt Tongue).

My problem was, some commands did not work (using the method above) and I tried to make it return to te main function after the command exit would be executed, but did not work also so I just droped the idea for now. Sad

Another idea I had, was to instead of using system() depending on user input, just run cmd.exe directly, but I do not yet know how to do that and I'll have to search more Smile


RE: "Switch" with string? - Frooxius - 12-01-2011

But that has nothing to do with a switch with a string in C++.

Also, what's the point of duplicating functionality of command line, when your program does nothing, just passes the input to another program?