在数组上使用字符串的switch语句 [英] Switch statement using string on an array
问题描述
#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)中那样聪明,您不能打开字符串(也不能比较) ==
的字符串).开关只能在整数类型(int
,char
等)上操作.
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(name[20])
的switch.这意味着switch(*(name + 20))
.换句话说,以名称打开第21个char
(因为第一个是name[0]
).由于name
只有20个字符,因此您正在访问名称后的任何内存. (这可能会发生不可预测的事情)
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]
(其中N
是strlen("kevin") + 1
).当您执行case "kevin"
时.仅当名称在与存储字符串完全相同的内存中时,它才起作用.因此,即使我将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\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)
.它会创建常见的安全问题使用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() {
name[MAX_LEN];
fgets(name, MAX_LEN, stdin);
...
这篇关于在数组上使用字符串的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!