C, if statements and strcmp

advertisements

I don't understand why it does not pick up on the inputs. It always displays "Invalid Input"... Help!

while(1)
{
    fgets(input, MAX, stdin);
    printf("%s", input);

    if(strcmp(input, "1") == 0)
    {
        add();
    }
    else if(strcmp(input, "2") == 0)
    {
        delete();
    }
    else if(strcmp(input, "3") == 0)
    {
        view();
    }
    else if(strcmp(input, "4") == 0)
    {
        break;
    }
    else
    {
        printf("Invalid Input!\n");
    }
}


Because the value stored by fgets() contains a trailing '\n'.

Try this

int stop = 0;
while (stop == 0)
{
    fgets(input, MAX, stdin);
    printf("%s", input);

    if (strcmp(input, "1\n") == 0)
        add();
    else if (strcmp(input, "2\n") == 0)
        delete();
    else if (strcmp(input, "3\n") == 0)
        view();
    else if (strcmp(input, "4\n") == 0)
        stop = 1;
    else
        printf("Invalid Input!\n");
}

did it work?

So you need to remove it from input or adding to the comparison string.