使用数组上的字符串切换语句 [英] Switch statement using string on an array

查看:16
本文介绍了使用数组上的字符串切换语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 语句.究竟如何解决问题?

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?

推荐答案

C 中的 Switch 语句不像其他语言(如 Java 7 或 Go)中的那样聪明,您无法打开字符串(也无法比较== 的字符串).Switch 只能对整数类型(intchar 等)进行操作.

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).

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

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)

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

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) {
        ...
    }

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

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
");
else if (ord == 0) 
    printf("str1 is the same as str2
");
else if (ord > 0)  
    printf("str1 is after str2 alphabetically
");

旁注:不要在该表单中使用 scanf("%s", name).它会创建一个 常见安全问题 像这样使用 fgets :(也是使用 scanf 的安全方法)

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);
    ...

这篇关于使用数组上的字符串切换语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆