如何在 C 语言的条件语句中使用字符串数组?
我想在 if 语句中使用字符串数组来测试输入字符串是否与数组中的任何字符串匹配。
到目前为止,这就是我尝试过的:
void checkForError(char input[50])
{
const char *input2[]={"print","loadStarter","terminate()"};
if(input != input2)
{
printf("Error:Incorrect method '%s'.\n",input);
}
else
{
abort();
}
}
如果我要在数组中输入“print”之类的内容,它最终会向我显示:
<块引用>错误:“打印”方法不正确。
但是当我尝试数组中未列出的内容(例如“g”)时,它会不停地重复错误消息。
我在想也许这样的事情可行:
void checkForError(char input)
{
if(strcmp(input,"print"))!=0 || strcmp(input,"loadStarter"))!=0 || strcmp(input,"terminate()")
{
printf("Error:Incorrect method '%s'.\n");
}
else
{
abort();
}
}
但事实证明这实际上行不通,所以我该怎么办?
I want to use a string array in an if statement to test whether the input string matches any of the strings in the array.
So far this is what I've tried:
void checkForError(char input[50])
{
const char *input2[]={"print","loadStarter","terminate()"};
if(input != input2)
{
printf("Error:Incorrect method '%s'.\n",input);
}
else
{
abort();
}
}
And if I were to enter something in the array like "print" it would end up showing me:
Error:Incorrect method 'print'.
but when I try something not listed in the array like "g" it repeats the error message nonstop.
I was thinking perhaps something like this could work:
void checkForError(char input)
{
if(strcmp(input,"print"))!=0 || strcmp(input,"loadStarter"))!=0 || strcmp(input,"terminate()")
{
printf("Error:Incorrect method '%s'.\n");
}
else
{
abort();
}
}
But it turns out that actually doesn't work so what do I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C 中,您不能使用
==
和!=
来比较字符串(有用);您必须使用库函数,例如strcmp
。请参阅如何比较“if”语句中的字符串?了解详情。You cannot compare strings (usefully) in C using
==
and!=
; you must use library functions such asstrcmp
instead. See How to compare strings in an "if" statement? for details.我认为解决你的问题的一个好办法是循环你的数组,在第一场比赛时中止。
这也比任何手动编码方法更容易扩展。
另外,如果您计划对这些字符串进行大量操作,并且字符串数量有限,那么您可能应该将它们转换为某种枚举。这样您就不必将 strcmp 分散到各处,并且可以使用标准的 switch 语句。
I think a good solution to your question would be to loop around your array, aborting on the first match.
This would also be easier to extend than any handcoded method.
Also, if you plan on doing a lot with these strings, and you have a limited number of strings, you should probably turn them into some sort of enum. This way you do not have to have strcmp scattered everywhere, and you can use a standard switch statement.
更好的方法是有一个返回值,然后让错误消息取决于返回值。
a better method would be to have a return value then have your error message depend on return value.
您的第二个想法是正确的,您不应该使用
==
运算符来比较字符串,无论如何,我不确定其余部分是否是拼写错误,但应该是这样的:Your second thought is correct, you should not compare the strings using
==
operator, anyway, I'm not sure whether the rest is a typo or not, but it should be like that: