Search code examples
cstringcomparestring.hstrncmp

how to compare character against set of given characters in C?


I'd like to be able to compare a character on stdin with a characters of my specification. The purpose of this is to filter out every other input as wrong, while maintaining only the specified single chars as commands. Like on stdin "nn" or "qddaw" -> wrong go again but "n" make something useful.

Here is what I have in mind "code-wise":

if (input does not contain 'c' or 's' or 'q' or 'n') { 
    printf("some kind of error");
}

Well I tried to create an array with specified characters like array[] = {'a', 'b', 'c'} so I could be able to compare it with a string on the stdin with function strncmp.. like

char c[256];
scanf("%s", c)
if (strncmp(array, c, 1) != 0) printf("error");

but it doesn't seem to work. Any suggestions?

Edit1: Here is actual piece of code:

char c[256];
char* s = "nsrld";
char* quiter = "q";

do 
    {
        printf(">");
        scanf("%s", c);
        if (only when there is no 'n' or 's' or other char from char* s on input)
        {
            errorHandle(ERROR_WRONG_CMD);
        }
        scanf("%*[^\n]"); scanf("%*c");
    } while (strcmp(c,quiter) != 0);

as you can see I handled the 'q' thing quite well, but multiple chars are pain in the ass. Thanks for any advice.

Edit 2: or in other words I need a function which will compare input with a set of given characters and only if there is one OR another (like 'q' or 's' the function will pass (but not if there are characters together like 'qs')


Solution

  • I didn't make myself clear enough. What I need is input "type what ever you want" like "wwqwqe" and do the error unless the input is just 'c' or just 's' (and a few more).

    char usersInput[200] = "";            /* A buffer to hold the input values */
    char *result = gets(usersInput);      /* Fill the buffer from stdin */
    if (result != NULL)                   /* If we got something */
    {
        if (strlen(usersInput) == 1)      /* the input must be exactly 1 character */
        {
            char ch = usersInput[0];
            if (strchr(ch, "csqn") == NULL)    /* It must be a valid values */
            {
                printf("Evil Bad Character <%c>\n", ch);
            }
            else
            {
                /* Do stuff with the known valid input value ch */
            }
        }
        else
        {
            puts("The input value must be exactly 1 character\n");
            puts("and must be 'c', 's', 'q' or 'n'");
        }
    }
    else
    {
        puts("EOF or ERROR while reading stdin\n");
    }
    

    This should do the job.

    One warning. gets is not smart enough to know that usersInput is 200 characters long.

    It will gleefully let you type in 201 characters or more, which overwrites other characters in memory. That sort of thing can lead to hard-to-find bugs.