gpt4 book ai didi

c - 如何使用 `switch` 语句比较 C 中的字符串?

转载 作者:太空狗 更新时间:2023-10-29 16:16:07 28 4
gpt4 key购买 nike

在 C 中有一个 switch 结构,它使我们能够根据测试整数值执行不同的代码条件分支,例如,

int a;
/* Read the value of "a" from some source, e.g. user input */
switch (a) {
case 100:
// Code
break;
case 200:
// Code
break;
default:
// Code
break;
}

对于字符串值,即 字符 *?

最佳答案

如果你的意思是,如何写类似这样的东西:

// switch statement
switch (string) {
case "B1":
// do something
break;
/* more case "xxx" parts */
}

然后 C 中的规范解决方案是使用 if-else 阶梯:

if (strcmp(string, "B1") == 0) 
{
// do something
}
else if (strcmp(string, "xxx") == 0)
{
// do something else
}
/* more else if clauses */
else /* default: */
{
}

关于c - 如何使用 `switch` 语句比较 C 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4014827/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com