c - 在数组上使用字符串的 Switch 语句

标签 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();
}

看来不行。这可能吗?我的意思是有什么方法可以使字符串的 switch 语句。实际上,如何解决问题?

最佳答案

C 中的 Switch 语句不像其他语言(例如 Java 7 或 Go)中的语句那样智能,您不能在字符串上切换(也不能将字符串与 == 进行比较)。 Switch 只能对整数类型(intchar 等)进行操作。

在您的代码中,您使用以下代码调用开关:switch(name[20])。这意味着 switch(*(name + 20))。换句话说,打开名称中的第 21 个 char(因为 name[0] 是第一个)。由于 name 只有 20 个字符,因此您正在访问 name 之后的任何内存。 (这可能会做不可预测的事情)

此外,字符串 "kevin" 被编译为 char[N](其中 Nstrlen("kevin") + 1) 其中包含字符串。当您执行 case "kevin" 时。仅当 name 位于存储字符串的同一 block 内存中时,它才会起作用。所以即使我将 kevin 复制到名称中。它仍然不匹配,因为它存储在不同的内存中。

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

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

字符串比较(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");

旁注:不要在该表单中使用 scanf("%s", name)。它创建了一个 common security problem像这样使用 fgets:(也有一种安全的方法可以使用 scanf)

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

关于c - 在数组上使用字符串的 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17984628/

相关文章:

string - 如何从 golang 中的字符串制作预告片?

将 int 转换为 char[]

python - 当指数为负时,为什么 numpy.power 不按元素对数组进行操作?

c++ - 通过函数参数获取数组

c++ - 删除一个 Char[]

c - 有没有办法将转义序列转换为字符串?

C#:我应该如何处理大数的算术?

c - 为其他类型重新利用相同的 c ADT

C语言: is double parse exist?

任何人都可以解释这两个分配之间的区别以及为什么好坏?