Kendall Weihe Kendall Weihe - 3 months ago 28
C Question

strtok() then strcmp() returning false when true

I'm guessing this is a type issue, so maybe you can show me how it is correctly done.

I'm reading command inputs from

stdin
and I want to quit when the user enters
q
.

I'm reading a user input from
stdin
using
fgets()
into a pointer to a character array. Then I splice off the first word using
strtok()
and assign it to another pointer to a character array. Then I compare it to a
q
in order to see if the user wants to quit the program by using the
strcmp()
function.

Here is some code:

char *input = (char*)malloc(32 * sizeof(char));
char *command = (char*)malloc(8 * sizeof(char));

while (strcmp(command, "q") != 0)
{
memset(input, 0, sizeof(input));
printf("Enter command: ");
fgets(input, 64, stdin);
command = strtok(input, " ");
//if I enter q --> printf("%d", strcmp(command, "q")) == 10
//if I enter w --> printf("%d", strcmp(command, "q")) == 6
}


What I want is, if
command == q
then
printf("%d", strcmp(command, "q"))
should equal
0
else it should print any other integer.

I should also note that I have verified
command
is being correctly assigned. In other words, when I enter
q
,
command == "q"
.

Answer

Maybe you can try this code:

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

int main()
{
    char *input = (char*)malloc(32 * sizeof(char));
    char *command = (char*)malloc(8 * sizeof(char));

    while (strcmp(command, "q") != 0)
    {
        memset(input, 0, sizeof(input));
        printf("Enter command: ");
        fgets(input, 64, stdin);
        command = strtok(input, " \n"); // Line corrected.
        //if I enter q --> printf("%d", strcmp(command, "q")) == 10
        //if I enter w --> printf("%d", strcmp(command, "q")) == 6
    }

return 0;

}
Comments