c switch字符串比较
时间: 2023-11-08 22:05:07 浏览: 70
C语言中,使用switch语句比较字符串可以通过strcmp函数实现,具体实现代码如下:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("请输入一个字符串:");
scanf("%s", str);
switch (strcmp(str, "hello"))
{
case 0:
printf("您输入的是 hello\n");
break;
default:
printf("您输入的不是 hello\n");
break;
}
return 0;
}
```
该程序通过scanf函数获取用户输入的字符串,然后使用strcmp函数将用户输入的字符串与字符串"hello"进行比较,得到比较结果后再使用switch语句判断比较结果,输出相应的提示信息。
相关问题
c语言switch字符串
在C语言中,switch语句不能直接匹配字符串,因为表达式必须是常量表达式,且必须是整型或者枚举类型。但是可以通过将字符串转换为整型或者枚举类型来实现switch语句匹配字符串的功能。例如,可以使用枚举类型来表示所有可能的字符串,然后使用switch语句匹配枚举类型。另外,也可以使用if-else语句来实现字符串的匹配功能。
示例代码:
```
#include <stdio.h>
#include <string.h>
enum COMMAND { OPEN, CLOSE, QUERY };
int main() {
char str[10];
enum COMMAND cmd;
printf("请输入命令:");
scanf("%s", str);
if (strcmp(str, "open") == 0) {
cmd = OPEN;
} else if (strcmp(str, "close") == 0) {
cmd = CLOSE;
} else if (strcmp(str, "query") == 0) {
cmd = QUERY;
} else {
printf("无效命令\n");
return 0;
}
switch (cmd) {
case OPEN:
printf("执行打开操作\n");
break;
case CLOSE:
printf("执行关闭操作\n");
break;
case QUERY:
printf("执行查询操作\n");
break;
default:
break;
}
return 0;
}
```
c语言用switch 比较字符串
在 C 语言中,switch 语句是用于多分支选择的一种语句,但是 switch 语句只能比较整型或字符型常量或变量,不能直接比较字符串。如果需要在 switch 语句中比较字符串,可以使用字符串比较函数 `strcmp()`,具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[20];
printf("请输入字符串:");
scanf("%s", str);
switch (strcmp(str, "hello")) {
case 0:
printf("字符串匹配:hello\n");
break;
case 1:
printf("字符串大于:hello\n");
break;
case -1:
printf("字符串小于:hello\n");
break;
default:
printf("字符串比较错误!\n");
break;
}
return 0;
}
```
在上面的代码中,我们用 `scanf()` 函数从标准输入中读入一个字符串,然后使用 `strcmp()` 函数将输入的字符串与 "hello" 进行比较。由于 `strcmp()` 函数返回值为整型,因此可以在 switch 语句中进行比较。如果字符串相等,返回值为 0,case 0 分支将被执行;如果字符串大于 "hello",返回值为 1,case 1 分支将被执行;如果字符串小于 "hello",返回值为 -1,case -1 分支将被执行。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)