[英]How do you use a string array in a conditional statement in 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();
}
}
但是事實證明實際上是行不通的,那我該怎么辦?
您不能使用==
和!=
比較C中的字符串(有用); 您必須改用諸如strcmp
庫函數。 請參閱如何比較“ if”語句中的字符串? 有關詳細信息。
我認為,對您的問題的一種好的解決方案是在數組周圍循環,在第一個匹配項時中止。
void checkForError(char* input)
{
const char *input2[]={"print","loadStarter","terminate()"};
const int len = sizeof(input2)/sizeof(input2[0]);
for (int i = 0; i < len ;i ++)
{
if (strcmp(input,input2[i]) == 0)
{
//I have matched the string input2[i]
abort();
}
}
// Nothing matched
printf("Not found\n");
}
這也比任何手工編碼的方法都容易擴展。
另外,如果您打算對這些字符串做很多事情,並且字符串數量有限,則可能應該將它們變成某種枚舉。 這樣,您不必將strcmp分散在各處,並且可以使用標准的switch語句。
您的第二個想法是正確的,無論如何,我不應該使用==
運算符比較字符串,我不確定其余的是否是錯字,但應該是這樣的:
void checkForError(char * input)
// ^ note the * (pointer)
{
if(strcmp(input,"print")!=0 || strcmp(input,"loadStarter")!=0 || strcmp(input,"terminate()") != 0)
// you forgot brackets
{
printf("Error:Incorrect method '%s'.\n", input);
// ^ you forgot the "input" parameter
}
else
{
abort();
}
}
更好的方法是有一個返回值,然后讓您的錯誤消息取決於返回值。
// return 1 when string is OK, 0 otherwise:
int checkForError(const char* input)
{
if(!strcmp(input,"print")) || !strcmp(input,"loadStarter")0 || !strcmp(input,"terminate()")
{
return 1;
}
else
{
return 0;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.