简体   繁体   中英

Check if input string exists in array of strings in C

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM