954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Switch Statement with String

I am making a program where the user has to input text, and the program outputs the appropriate string.

I made this program using if else statement, but professor said not to use if and else.

So I want to know if I can use the switch statement.

I know that switch statement work for char and int only. (As from what I read from the book).

So far I got this:

#include <iostream>
#include <string>
using namespace std;

int main (void)
{
char word;
cout<< "Enter word to define: \n";
word = getchar();

switch (word){
case 'd':
    cout<< "A four legged animal";
    break;
case 'c':
    cout<< "A animal scared of water";
    break;
default:
    cout<< "not in dictionary";
}
return 0;
}


It was actually

case 'dog'
case 'c' etc...but when i type a word it shows the default.

It works for the first character, which is of no use since there may be other words starting with the same character.

This program is a dictionary program, I have recieved helped about a few weeks back with it using if else, but like i mentioned professor did not want it that way...if the switch statement does not result, I might have to use structures as that is what th professor used in his code in which I took a glimpse at.

tformed
Junior Poster in Training
58 posts since May 2007
Reputation Points: 21
Solved Threads: 1
 

you can not use switch with strings.

>>word = getchar();
Don't use getchar() is c+++ programs. use cin.get() instead.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

You don't need to use switch at all, try the STL map container instead, where you can link strings to other strings (just like in a dictionary)

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

Bench has given a good suggestion. But if you are not allowed to use maps, try using two parallel string arrays in which the location of the name of the animal and its description resides in the same location in their respective arrays.

const int SIZE = 3;
string animal[SIZE] = {"dog", "cat", "pig"};
string desc[SIZE] = {"bark", "meow", "oink"};

bool found = false;
for(int i = 0; i < SIZE; ++i)
{
    if(animal[i] == input)
    {
        cout << animal[i] << " -> " << desc[i];
        found = true;
        break;
    }
}
if(!found)
    cout << "No such animal exists";



I know this looks like a lot of work for a single user input, but is just another way of doing things, plus this is much more flexible approach instead of the hard-coded 'if...else' or 'switch' constructs. Since you are under going a programming course, I guess the focus would be more on logic and uniqueness than efficiency.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Thank you all for your help, I have decided to use maps, I got some help from the text book and managed to get it working, if the professor does not accept the map method then I will do the way that SOS mentioned, as I looks simpler and shorter than the maps.


Now I have to get it to loop so that the program won't quit after it defines one word.

When I use the for loop it displays the definition 5 times lol.

My code thusfar:

#include <iostream>
#include <map>
#include <string>
using namespace std;

class x

{    char str [40];
    public:
        x () {strcpy (str,"");}
        x (char *s) {strcpy (str,s);}
        char *get(){return str;}
};

bool operator< (x a, x b)

{    return strcmp (a.get(),b.get())<0;
}

class y 
{    char str [80];
    public:
        y() {strcmp(str, "");}
        y (char *s) {strcpy (str,s);}
        char *get () {return str;}
};

int main ()
{    map <x, y> mappy;

    mappy.insert (pair<x, y> (x ("dog"), y("Lassie")));
    mappy.insert (pair<x, y> (x ("cat"), y("Garfield")));
    mappy.insert (pair<x, y> (x ("whale"), y("Free Willy")));
    mappy.insert (pair<x, y> (x ("fox"), y("firefox")));
    mappy.insert (pair<x, y> (x ("bird"), y("eagle")));
    mappy.insert (pair<x, y> (x ("puma"), y("shoe brand")));
    mappy.insert (pair<x, y> (x ("lion"), y("lion king")));
    mappy.insert (pair<x, y> (x ("mouse"), y("mickey mouse")));

    char str [80];

    cout << "Enter word: \n";

cin>> str;

map <x, y>:: iterator p;

p = mappy.find (x(str));


if (p != mappy.end())

{    cout<< "" <<p-> second.get();
    cout<< "\n\n";
}
else
cout << "Not here, type again. \n";

return 0;

}


any suggestions on how to trim and how to loop it, and user presses EX to exit, would greatly help.

thanks everyone.

tformed
Junior Poster in Training
58 posts since May 2007
Reputation Points: 21
Solved Threads: 1
 

If you wanted to make the code smaller, you can use the C++ library. (you have it at your disposal, so you may aswell use it..!)

#include <map>
#include <string>

typedef std::pair<std::string, std::string> entry_t;
typedef std::map<std::string, std::string> dictionary_t;

int main()
{
    const entry_t init[] =
    {
            entry_t( "dog", "four legged pet" ),
            entry_t( "fish", "swims in the sea"),
            entry_t( "clock", "tells the time"),
            entry_t( "radio", "plays music")
    };
    const int entries( sizeof(init) / sizeof(*init) );
    dictionary_t dictionary( init, init+entries );
}


As for the looping issue, the easiest way might be to perform a do...while( str != "EX" )

(the != comparator also only works when 'str' is a C++ string. this is another reason to ditch the char arrays)

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

working on my setup here

#include <iostream>
#include <map>
#include <string>
using namespace std;
class x
{    char str [40];
    public:
        x () {strcpy (str,"");}
        x (char *s) {strcpy (str,s);}
        char *get(){return str;}
};
bool operator< (x a, x b)
{    return strcmp (a.get(),b.get())<0;
}
class y 
{    char str [80];
    public:
        y() {strcmp(str, "");}
        y (char *s) {strcpy (str,s);}
        char *get () {return str;}
};
int main ()
{    map <x, y> mappy;
    mappy.insert (pair<x, y> (x ("dog"), y("Lassie")));
    mappy.insert (pair<x, y> (x ("cat"), y("Garfield")));
    mappy.insert (pair<x, y> (x ("whale"), y("Free Willy")));
    mappy.insert (pair<x, y> (x ("fox"), y("firefox")));
    mappy.insert (pair<x, y> (x ("bird"), y("eagle")));
    mappy.insert (pair<x, y> (x ("puma"), y("shoe brand")));
    mappy.insert (pair<x, y> (x ("lion"), y("lion king")));
    mappy.insert (pair<x, y> (x ("mouse"), y("mickey mouse")));
    char str[80] = { '\0' };
    cout << "Enter word: \n";
    while (cin.getline(str, 80)) {
        if ( std::char_traits<char>::compare(str,"quit",4) == 0 )
            break;
        map <x, y>:: iterator p;
        p = mappy.find (x(str));
        if (p != mappy.end()) {    
            cout << "" <<p-> second.get();
            cout << "\n\n";
            cout << "Enter word: \n";
        }
        else
            cout << "Not here, type again. \n";
        //reset the char[] to null on all values, this is because
        //after a loop if the user does not enter a value larger than
        //the previous then there will be left over garbage in the char[]
    }
    return 0;
}
Killer_Typo
Master Poster
781 posts since Apr 2004
Reputation Points: 152
Solved Threads: 39
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You