Comparing two strings, problems with strcmp

浪尽此生 提交于 2019-12-12 15:53:21

问题


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?


回答1:


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)




回答2:


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.




回答3:


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")



回答4:


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.



来源:https://stackoverflow.com/questions/19479232/comparing-two-strings-problems-with-strcmp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!