Hello 2 questions.....

1) I just tried to code a switch statement with a stribg but my compiler throws up error messages....

2) Is they anyway I can convert a string to an int and then back to a string?

cheers

Recommended Answers

All 15 Replies

Post some code...

switch statements work only on integer values.
In Java the values you switch on also are required to be constant values (either integer literals or defined constant values), C++ might be more relaxed about that.

If the string represent an integer (for example "1") you can use itoa to turn it into an int.
If it doesn't there's no easy way, but you could use a hashtable with the strings as keys and integer constants as values and switch on the value found in that hashtable.

#include <iostream>
#include <cstring> //string header

using namespace std;

int main()

{

int a = 0; //set to 1 if found
int b = 0; //set to 1 if found

char string[] = "Hello";
char string2[10];

cin >> string2;

switch (string2) 
	{
	case 'hello':

	if (string2 == "hello")
	cout << "Its identical to string" <<endl;
	break;

	case 'GOODBYE':

	if (string2 == "GOODBYE")
	cout << "string 2 says goodbye , string 1 says hello"<<endl;
	break;

	}

	return 0;

	}

since this doesnt work I thougt that if i convert the string entered from char to numbers (ints) i could use an if

if a ==435
cout<< "true";
else
cout << "false";

kinda thing

I see... For switch see jwenting's post.
For comparing strings, use strcmp not ==

umm... ok can you not convert the chars into numbers?

If you just want a more readable switch/case, simply use enumerations.

// example of enumeration   enum name { list, ....... }

#include <stdio.h>    // in/out and file functions

enum days { sun,mon,tue,wed,thu,fri,sat };   // sun = 0  etc.

int main()
{
  enum days week;

  for (week = sun; week <= sat; week++) {   // used like integer constants
    // enumerations make switch/case easier to read
    switch (week) {
      case sun : puts("Sunday"); break;
      case mon : puts("Monday"); break;
      case tue : puts("Tuesday"); break;
      case wed : puts("Wednesday"); break;
      case thu : puts("Thursday"); break;
      case fri : puts("Friday"); break;
      case sat : puts("Saturday"); break;
    }
  }
  getchar();
  return 0;
}

cool.... thanks mate now i can continue my conquer in the world of c++ I do hope you guys dont mind me posting this stuff just trying to deepen my knowledge of c


could this be adatped to say if xxxx is entered into string??

cool.... thanks mate now i can continue my conquer in the world of c++ I do hope you guys dont mind me posting this stuff just trying to deepen my knowledge of c


could this be adatped to say if xxxx is entered into string??

Please make this conquest a little more clear ...

Please make this conquest a little more clear ...

Sorry could this be adapted , so that a string of charatcers are entered, ie say Monday, and it returns something? I'm just wondering since you've used
"puts" what ever that means...

i was thinking something amoungst the lines

#include < iostream>
#include < cstring>


enum days { sun,mon,tue,wed,thu,fri,sat };   // sun = 0  etc. 

int main() 
{ 

char string[10];
cin << string;
  enum days week; 

  for (week = sun; week <= sat; week++) {   // used like integer constants 
    // enumerations make switch/case easier to read 
    switch (week) { 
      case sun : 
 cout << "Found sunday";
 break;

    case mon :
cout << "Found monday";
break;

case Tue :
cout << "found tuesday";
break;

default:
cout << "your string wasn't matched!";
break;
    } 
  } 
  getchar(); 
  return 0; 
}

I think what you are asking (please clarify if I'm wrong) is to map the ascii representation of a string into a number you can use in your switch. This isn't very clean, but can be done. But, there are limits. For example, a short is usually 2 bytes in size, so you could compare any 2 byte string mapped into a short. Likewise a long is 4 bytes so you could compare a 4 byte string. That's pretty limiting.

A better way to accomplish what you want is to have a table of strings and their values, and then look up the entered text in the table and use the corresponding value in your switch. Something like this:

// note: this is not tested, so consider it pseudocode...

enum AUserCommand { CommandUnknown, CommandHello, CommandGoodby };

static const struct
{
    const char* name;
    AUserCommand command;
} commandTable[] =
{
    { "hello", CommandHello },
    { "goodbye", CommandGoodBy },
};

AUserCommand LookupUserCommand( const char* whatUserEntered )
{
    int i;
    for (i = 0; i < (sizeof(commandTable) / sizeof(commandTable[0])); i++)
    {
        if (stricmp( whatUserEntered, commandTable[i].name) == 0)
            return commandTable[i].command;
    }
    return CommandUnknown; // not a known command
}

You can then use the returned enum in your switch statement. This code is overkill for two commands, of course, but as you add more commands you simply add an enum and an entry in the table and you are ready to handle the input.

woah hell that looks very complex but your first idea was correct if I understand rightly what your getting at an int is 4 byes... a char is 1 byte per char, so perhaps if i narrowed the chars entered to 3 values then it will be 4 bytes .... Just don't know how to do this

Hee hee, well, if you insist....

Here's one way:

#define STRING_TO_INT(s1,s2,s3,s4) ((s1 << 24) | (s2 << 16) | (s3 << 8) | s4)

switch (STRING_TO_INT( command[0], command[1], command[2], command[3] ))
{
    case STRING_TO_INT( 'H', 'E', 'L', 'L' ): // hello
    ....
    break;

    case STRING_TO_INT('B', 'Y', 'E', 0 ): // bye
    ....
    break;
}

You need a #define rather than a routine so it can be a constant. If you have one or two byte commands, you'll have to make sure and pad 'command' out to 4 bytes with nulls.

woah ok maybe not since this is far beyound my stuff!! I'll see if I can modify my binary search program to accept strings and not ints but thanks all the same ;)

U cant use strings in switch statement ....the cases accept only single character or a integer ... if u still wants to use strinngs in cases of switch u have to tkae help of some string.h functions such as strcmp or strcpy acc. to ur requirements in the codes

Are you trying to see if the users input string matches any string in a separate list? (read carefully)

if so it is basically:

#include <cstring> // c++ ANSI string, much better :)

string valid_strings [] = { your strings here....... };

and in the main:

bool valid = false;
string str;
cin >> str;

for(int i = 0; i < how many valid strings you typed; i++)
{
    if(str == valid_strings[i]) // != CAN be done with ansi string, for char strings use strcmp
        valid = true;
}

if(valid)
    cout << "Found the string!";
else
    cout << "Your string doesnt match!";

btw this is a sequential search: there are better ways of searching through strings!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.