Switch statement using string on an array
Solution 1
Switch statements in C aren't smart like one's found in other languages (such as Java 7 or Go) you cannot switch on a string (Nor can you compare strings with ==
). Switch can only operate on integral types (int
, char
, etc).
In your code you call switch with: switch(name[20])
. That means switch(*(name + 20))
. In other words switch on the 21st char
in name (because name[0]
is the first). As name
only has 20 chars you are accessing whatever memory is after name. (which could do unpredictable things)
Also the string "kevin"
is compiled to a char[N]
(where N
is strlen("kevin") + 1
) which contains the string. When you do case "kevin"
. It will only work if name is in the exact same piece of memory storing the string. So even if I copied kevin
into name. It still would not match as it is stored in a different piece of memory.
To do what you seem to be trying you would do this:
#include <string.h>
...
if (strcmp(name, "kevin") == 0) {
...
}
String compare (strcmp
) returns different values based on the difference in the strings. Eg:
int ord = strcmp(str1, str2);
if (ord < 0)
printf("str1 is before str2 alphabetically\n");
else if (ord == 0)
printf("str1 is the same as str2\n");
else if (ord > 0)
printf("str1 is after str2 alphabetically\n");
Side note: Dont use scanf("%s", name)
in that form. It creates a common security problem use fgets
like this: (there is a safe way to use scanf
too)
#define MAX_LEN 20
int main() {
char name[MAX_LEN];
fgets(name, MAX_LEN, stdin);
...
Solution 2
Switch statements work on int
values (or enum
), but not on char
arrays.
You could do
if (strcmp(name, "kevin")==0) {
printf("hello");
}
else if (strcmp(name, "Laura")==0) {
printf("Allo");
}
else if (strcmp(name, "Mike")==0) {
printf("Good day");
}
else {
printf("Help!");
}
Solution 3
There are plenty of ways to go about this! For example, use a...
3-letter hash
#include <stdio.h>
int main(){
char name[20];
printf("enter a name ");
scanf("%s",name);
switch((int)*name * (int)*(name+1) * (int)*(name+2)){
case (1275226) : // "kevin"
printf("hello %s.\n", name);
break;
case (1293980) : // "astro"
printf("welcome %s.\n", name);
break;
}
printf("%d",(int)*name * (int)*(name+1) * (int)*(name+2));
}
Comments
-
PNC almost 2 years
#include<stdio.h> int main(){ char name[20]; printf("enter a name "); scanf("%s",name); switch(name[20]){ case "kevin" : printf("hello"); break; } printf("%s",name); getch(); }
It seems it will not work. Is this possible? I mean is there any way we can make a switch statement of a string. How to solve the problem, actually?
-
autistic over 10 yearsWhich book are you reading? I ask this because those who read books usually don't have this question; The book answers it. If you're not using a book as a guide, then you're probably a liability; Stop learning C, and learn a programming language that doesn't allow you to accidentally shoot yourself in the feet. Alternatively, get yourself a book... (duh, hintedy hint)
-
PNC over 10 yearsim not reading any book :) uh.. c language is our lesson and we have a project about it. yeah i want to stop learning this we are just forced to do so :))
-
Jiminion over 7 yearsIsn't name[20] undefined?
-
-
This isn't my real name over 10 yearsPlease note that string literals do not compile to
const char *
. String literals are arrays of char, and have typechar[n]
wheren
is one more than the number of bytes in the string ("ABCD"
has four bytes, so it would be of typechar[5]
), and when used in a pointer context, they evaluate to pointers which are of typechar *
. It is true that you aren't allowed to modify their content, but for historical reasons they do not haveconst
type. -
Triss Healy over 10 yearsCheers, changed the text to fix that. I wasn't sure if C recognized string literals as const as C++ seems to, C won't complain about loosing const-ness.
-
This isn't my real name over 10 yearsIncidentally, here's a subtlety for you. While it is true that the string literal
"kevin"
is an arrayN
ofchar
whereN
is equal tostrlen("kevin") + 1
, this does not hold true for all string constants. Consider the perfectly valid string constant"degenerate\0string\0constant"
, which (if I've counted correctly) is is an array 27 ofchar
, not an array 11 ofchar
. -
jjxtra over 9 yearsFor strings of length 8 or less you should be able to switch on a unsigned long long by bit shifting each char.