c - Switch statement using string on an array -


#include<stdio.h>  int main(){      char name[20];      printf("enter name ");     scanf("%s",name);     switch(name[20]){         case "kevin" :          printf("hello");         break;     }     printf("%s",name);     getch(); } 

it seems not work. possible? mean there way can make switch statement of string. how solve problem, actually?

switch statements in c aren't smart one's found in other languages (such java 7 or go) cannot switch on string (nor can compare strings ==). switch can operate on integral types (int, char, etc).

in code call switch with: switch(name[20]). means switch(*(name + 20)). in other words switch on 21st char in name (because name[0] first). name has 20 chars accessing whatever memory after name. (which unpredictable things)

also string "kevin" compiled char[n] (where n strlen("kevin") + 1) contains string. when case "kevin". work if name in exact same piece of memory storing string. if copied kevin name. still not match stored in different piece of memory.

to seem trying this:

#include <string.h> ...     if (strcmp(name, "kevin") == 0) {         ...     } 

string compare (strcmp) returns different values based on difference in strings. eg:

int ord = strcmp(str1, str2); if (ord < 0)       printf("str1 before str2 alphabetically\n"); else if (ord == 0)      printf("str1 same str2\n"); else if (ord > 0)       printf("str1 after str2 alphabetically\n"); 

side note: dont use scanf("%s", name) in form. creates common security problem use fgets this: (there safe way use scanf too)

#define max_len 20 int main() {      name[max_len];      fgets(name, max_len, stdin);     ... 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -