Search code examples
cstrcmpstrcpy

Comparing two strings, problems with strcmp


I'm trying to check if the line read from stdin begins with "login:" but strcmp does not seem to work.

char s1[20], s2[20];
fgets(s1, 20, stdin);
strncpy(s2,s1,6);
strcmp(s2, "login:");
if( strcmp(s2, "login:") == 0)
    printf("s2 = \"login:\"\n");
else
    printf("s2 != \"login:\"\n");

I don't care what comes after "login:", i just want to make sure that's how the command is given. What am i doing wrong?


Solution

  • strcmp returns 0 if the two strings are exactly the same to accomplish what you want to do

    Use :

    strstr(s2 , "login:")

    (It return NULL if the string doesn't exist in s2)

    or

    strncmp(s2 , "login:" , 6)

    This will compare the first 6 characters (if s2 begins with "login:" , it will return 0)