假设我有一个数组,其中包含在快餐店购买的各种物品的名称。。。
char options[8][15] = {"burger", "fries", "pop", "apples", "vegan burger", "vegan fries"};
以及一个未初始化的变量,它将保存客户的订单。。。
char choice[15];
我使用函数exists_in_array()
来遍历选项数组,并检查选择变量是否与数组中包含的任何字符串匹配。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
...
int exists_in_array(char value[], char (array) [8][15])
{
for(int i = 0; i < 8; i++)
{
if(strcmp(value, array[i]) == true)
{
return true;
}
}
return false;
}
...
int main(void)
{
char options[8][15] = {"burger", "fries", "pop", "apples", "vegan burger", "vegan fries"};
char choice[15];
printf("Enter your choice: ");
fgets(choice, 15, stdin);
strtok(choice, "n"); // Removing the trailing newline that gets recorded with fgets
if (exists_in_array(choice, options))
{
printf("That is a valid option");
}
else
{
printf("That is not a valid option");
}
}
我目前没有收到任何错误消息,但唯一会返回That is a valid option
的选项是burger
。其他项目都会说That is not a valid option
,我不明白为什么会发生这种情况。它不能是用fgets()
添加的换行符,因为我使用strtok()
来立即删除它。
有人能帮我弄清楚吗?
来自strcmp()
:的文档
strcmp()
返回一个整数,表示比较结果,如下所示:
- 0,如果字符串
s1
和s2
相等- 如果CCD_ 11小于CCD_
- 如果CCD_ 13大于CCD_
您的支票应该是:
if (!strcmp(value, array[i])) { // ...
// Or, more explicitly:
if (strcmp(value, array[i]) == 0) { // ...
int exists_in_array(const char *value, char **options)
{
while(options && *options)
{
if(!strcmp(value, *options))
{
return true;
}
options++;
}
return false;
}
int main(void)
{
char *options[] = {"burger", "fries", "pop", "apples", "vegan burger", "vegan fries", NULL};
char choice[15];
printf("Enter your choice: ");
fgets(choice, 15, stdin);
if(*choice) choice[strlen(choice)] = 0;
if (exists_in_array(choice, options))
{
printf("That is a valid option");
}
else
{
printf("That is not a valid option");
}
}