4

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?

John
  • 449
  • 5
  • 12
Barsan Ionut
  • 45
  • 1
  • 1
  • 6
  • 1
    `strcmp` is for **exact** matches. I suggest perusing the [C string library](http://en.cppreference.com/w/c/string/byte) to see if there's another function you could use for this task... – Oliver Charlesworth Oct 20 '13 at 15:32
  • I am copying the first 6 characters (which should be "login:") into another string that is going to be compared with the string "login:", so i am going for an exact match. – Barsan Ionut Oct 20 '13 at 15:38
  • Oh that's a fair point; I hadn't noticed that. – Oliver Charlesworth Oct 20 '13 at 15:40

4 Answers4

6

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)

P0W
  • 46,614
  • 9
  • 72
  • 119
Farouq Jouti
  • 1,657
  • 9
  • 15
1

Every string in C is followed be a null terminator, which shows

when the end of a string occurs.

Right now, you're copying 6 letters from s1 to s2, which is

login:

this means that you aren't copying the null terminator.

So s2 isn't exactly going to be "login:" as you wanted it to be.

so I suggest rather using

strstr(s2, "login:")

to check if login: is contained in s2.

Se Won Jang
  • 773
  • 1
  • 5
  • 12
0
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");

You compare your String with "login" which includes the following characters: 'l''o''g''i''n'':''\0' So if the Strings should be equal there have to be a '\0' in s2. The following Code should work:

char s1[20], s2[20];
fgets(s1, 20, stdin);
strncpy(s2,s1,6);
s2[6]='\0'; //end of String
strcmp(s2, "login:");
if( strcmp(s2, "login:") == 0)
    printf("s2 = \"login:\"\n");
else
    printf("s2 != \"login:\"\n")
Benedikt Bock
  • 1,007
  • 15
  • 37
-1

string library <string.h> in c contains two functions strcmp(s1,s2) and strcmpi(s1,s2). strcmp function can not compare strings by length. it compares ascii values of first character of string and if i m providing s1="Login" and s2="Sign out" then it returns negative value because ascii of 'L' is less than ascii of 'S'. if first characters are same than it goes for checking 2nd.

awh112
  • 1,466
  • 4
  • 22
  • 34