Why is my strcmp() failing?

北战南征 提交于 2019-12-13 05:25:55

问题


I am a C newbie and learning string tokenizing. I am trying to compare two strings in the following way. But the string comparison I am doing is failing.

Can you please let me know what I am missing here?

I couldn't find another similar question, may be due to my inexperience in C. If one exists, can you please redirect me to it?

char* input = "comparer here";

char* args[5];

int counter = 0;
char *tok = strtok(input, " ");
while (tok != NULL) {
   args[counter] = tok;
   counter ++;
   if (counter == 5)
     break;
   tok = strtok(NULL, " ");
}

char* comp_str = "comparer";    
if (strcmp(args[0], comp_str) == 1) {
        // do some stuff
}

回答1:


It fails because strcmp (and its siblings) returns a zero value if they are equal, a negative value if the first is less than the second, and a positive value if the first is greater than the second.

The negative or positive value is not specified. In most implementations it is the difference of the first different characters. But that is not guaranteed.

Comparing the result to 1 is very unlikely to succeed.




回答2:


You are defining a string called input, but using a variable called message, undefined.




回答3:


strcmp() returns 0 when the two strings to be compared are equal. You should change 1 to 0 if you are trying to check if the two strings are equal.



来源:https://stackoverflow.com/questions/30720533/why-is-my-strcmp-failing

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