switch case blues: case? (should be quick solver)

Oy mates, I'm sucking it up lately. This should be a quick solve for someone who knows whats going on (or who can find an example that deals with it that is diff from what I've done)

Basically a command comes in, depending on the command I need to do different things. so if the user types "hello and then anything here for long time" I would want to go to one case and run a particular function (based on the first word 'hello').

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   void message(char * message){

	   int cnt = strcspn(message," ");
	   char *messageSW;
	   strncpy(messageSW,message,cnt);
	   
	   switch(*messageSW){
		   case "hello":
			   printf("hello switch");
			   break;
		   default:
			   printf("nothing switch");
			   break;
	   }


   }


Is this pretty much impossible and should just use a series of if(strncmp==0) kind of thing? Just seems so messy.
by the way, i'm getting an error on the line "case hello:" (line 8). The error says "case expression not constant".

so is there a simple way to make "hello" constant?
You cannot use strings on switch/case statements. Anyway, to fix that you would have to make a splitter function that would split at the first space (or at a certain character length) and then (probably) return the string of the first word (characters). Then you can check that with ifs/else ifs and do whatever else you need to.

1
2
3
4
5
6
7
8
9
10
11
//something like this
void handlemsg(string message) {
     string buffer = split(message);
     if (buffer == "hello") {
           //hello
     } else if(buffer == "lol") {
           //lol
     } else {
           //...
     }
}
Well, I saw an example online where somebody supposedly did it, but it didn't work for me. So i think there must be a way to do it, but regardless:

the way i would do you're solution is to use the function strncmp i mentioned above. compare so many characters of each string. int count = strcspn(buffer," ") returns the number of chars till the first space, so then you'd call if(strncmp(buffer,"hello",count)==0) essentially.
You could do it that way, although since I used strings, I just used the .find() and then cut off everything after the space using resize().
Topic archived. No new replies allowed.