I'm new to C and I'm trying to solve a problem.
I want to ask for user to insert 5 colors in an array but want to check if string exists on the existing array (allowed colors), or not before it is added.
I've tried with strcmp
and some other ways but can figure out how to do it.
Any help would be appreciated.
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *colors[] = {
"green",
"red",
"blue",
"yellow",
"brown",
"white",
"black"
};
int n = 5, i, num, size = 7;
char input[5][7];
int main() {
char *str = (char *)malloc(sizeof(char) * size);
printf("Add 5 colors:\n ");
for (i = 0; i < n; i++) {
scanf("%s", input[i]);
strcpy(str, input[i]);
if (strcmp(colors[i], str) == 0) {
printf("Exists!\n");
}
}
for (int i = 0; i < n; ++i) {
printf("%d %s\n", 1 + i, input[i]);
}
return 0;
}