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;
}
7
  • Your code doesn't compile. Please provide a minimal, reproducible example, see stackoverflow.com/help/minimal-reproducible-example. Commented Dec 4, 2021 at 10:58
  • August Karlstrom, thanks. Iǘe donne that. Commented Dec 4, 2021 at 11:42
  • There is still a syntax error in your code. You also need to include the required header files. Commented Dec 4, 2021 at 11:46
  • I have compiled with 2 diferent compilers and Iḿ getting no error. Can you please tell me what is? Commented Dec 4, 2021 at 12:03
  • Does this answer your question? How to check if a string is in an array of strings in C? Commented Dec 4, 2021 at 17:33

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.