Switch statement using string on an array

前端 未结 8 1426
礼貌的吻别
礼貌的吻别 2021-01-13 06:28
#include

int main(){

    char name[20];

    printf(\"enter a name \");
    scanf(\"%s\",name);
    switch(name[20]){
        case \"kevin\" : 
             


        
8条回答
  •  广开言路
    2021-01-13 07:27

    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 
    ...
        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() { 
        name[MAX_LEN]; 
        fgets(name, MAX_LEN, stdin);
        ...
    

提交回复
热议问题