使用数组上的字符串切换语句

PNC*_*PNC 5 c arrays string switch-statement

#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();
}
Run Code Online (Sandbox Code Playgroud)

它似乎不起作用.这可能吗?我的意思是我们有什么方法可以创建一个字符串的switch语句.实际上如何解决问题?

Tri*_*aly 8

C中的switch语句不像其他语言(例如Java 7或Go)中的那样,不能打开字符串(也不能比较字符串==).交换机只能在整数类型(操作int,char等等).

在你的代码调用交换机:switch(name[20]).这意味着switch(*(name + 20)).换句话说,char在名称上打开21 (因为name[0]是第一个).因为name只有20个字符,你正在访问名字后的内存.(这可能做不可预测的事情)

字符串也"kevin"被编译为包含字符串的char[N](where Nis strlen("kevin") + 1).当你这样做case "kevin".它只有在名称与存储字符串的内存完全相同时才有效.所以,即使我复制kevin到名字.它仍然不匹配,因为它存储在不同的内存中.

要做你似乎尝试的事情,你会这样做:

#include <string.h>
...
    if (strcmp(name, "kevin") == 0) {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

String compare(strcmp)根据字符串的不同返回不同的值.例如:

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");
Run Code Online (Sandbox Code Playgroud)

旁注:不要scanf("%s", name)以那种形式使用.它创建了一个共同的安全问题,使用fgets这样的:(有使用安全的方式scanf太)

#define MAX_LEN 20
int main() { 
    name[MAX_LEN]; 
    fgets(name, MAX_LEN, stdin);
    ...
Run Code Online (Sandbox Code Playgroud)


chu*_*ica 6

Switch语句适用于int值(或enum),但不适用于char数组.

你可以做到

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!");
}
Run Code Online (Sandbox Code Playgroud)