Say that I have an array that holds the names of various items for purchase at a fast food place...
char options[8][15] = {"burger", "fries", "pop", "apples", "vegan burger", "vegan fries"};
and an uninitialized variable that will hold the customer's order...
char choice[15];
I am using a function exists_in_array()
to iterate through the options array and check if the choice variable matches any of the strings contained inside the 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");
}
}
I am not getting any error messages at the moment, but the only option that will ever return That is a valid option
is burger
. Every other item will say That is not a valid option
and I can't figure out why this is happening. It can't be the newline character that gets added with fgets()
because I use strtok()
to remove it immediately afterwards.
Can anyone help me figure this out?