0

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Bruno
  • 27
  • 5
  • Your code doesn't compile. Please provide a minimal, reproducible example, see https://stackoverflow.com/help/minimal-reproducible-example. – August Karlstrom Dec 04 '21 at 10:58
  • August Karlstrom, thanks. Iǘe donne that. – Bruno Dec 04 '21 at 11:42
  • There is still a syntax error in your code. You also need to include the required header files. – August Karlstrom Dec 04 '21 at 11:46
  • I have compiled with 2 diferent compilers and Iḿ getting no error. Can you please tell me what is? – Bruno Dec 04 '21 at 12:03
  • Does this answer your question? [How to check if a string is in an array of strings in C?](https://stackoverflow.com/questions/13677890/how-to-check-if-a-string-is-in-an-array-of-strings-in-c) – Robert Harvey Dec 04 '21 at 17:33
  • Hey Robert Harvey, yes it helps but I still didnt figure out why strcmp fails. just changed the code here to what iǘe tried. Thanks for the link. – Bruno Dec 04 '21 at 23:42
  • @Bruno Your code had a missing brace but I see that it has been corrected now. – August Karlstrom Dec 06 '21 at 11:06

1 Answers1

0

You should add a nested loop to compare the input with every string in the reference array:

#include <stdio.h>
#include <string.h>

const char *colors[7] = {
    "green",
    "red",
    "blue",
    "yellow",
    "brown",
    "white",
    "black",
};

int main() {
    int n, i, j, num, size = 7;
    char input[5][8];

    printf("Add 5 colors:\n ");

    n = 0;
    while (n < 5) {
        if (scanf("%7s", input[n]) != 1)
            break;

        for (int j = 0; j < 7; i++) {
            if (strcmp(input[n], colors[j]) == 0) {
                printf("Exists!\n");
                n++;
                break;
            }
        }
    }
    for (int i = 0; i < n; ++i) {
        printf("%d %s\n", 1 + i, input[i]);
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189