strcmp不给0,但是两个参数是一样的 [英] strcmp doesnt give 0, but the two args are the same
问题描述
void contains(NODE * head,char * user)
{
NODE * this = head;
while(this!= NULL)
{
strcpy(temp,this-> data);
// printf(%s\\\
,user);
// printf(%s\\\
,temp);
printf(%d test\\\
,strlen(user));
printf(%d node\\\
,strlen(temp));;
printf(%d\\\
,strcmp(temp,user));
if(strcmp(this-> data,user)== 0){
printf(Found data%s\\\
,this-> data);
}
this = this-> next;
}
}
我在main(包含被调用最后一行):
NODE * head;
head = malloc(sizeof(NODE));
bool headNode = true;
char userID [1000];
char userIDsearch [180];
char test [180] =monkey;
while((fgets(userID,1000,stdin)!= NULL)){
// printf(%s\\\
,userID);
if(headNode == true)
{
head = insert(NULL,userID);
headNode = false; //这是用来首次将数据插入到我的链表中
}
else
{
head = insert(head,userID);
}
}
包含(头,测试);
strcmp
如果我输入猴子,但它给出1.另外,我测试和使用 strlen
在我正在比较的两个字符串,由于某些原因 strlen
为 temp
(我的输入)提供长度+ 1,但 strlen
为〜user`提供正确的长度(我设置为字符串猴子)。
不要忘记 fgets )
保留换行符,但是您没有将其删除,或者添加到 test
的末尾。
如果您使用以下语句打印输入,则可以发现:
printf(User ID <%s>> \\\
,userID);
在循环内。 <
和>>
显示字符串的起始和结束位置,并显示嵌入的换行。
I can't see what I'm doing wrong.
void contains(NODE *head, char *user)
{
NODE *this = head;
while(this != NULL)
{
strcpy(temp, this->data);
// printf("%s\n",user);
// printf("%s\n",temp);
printf("%d test\n", strlen(user));
printf("%d node\n", strlen(temp));;
printf("%d\n",strcmp(temp, user));
if(strcmp(this->data, user) == 0){
printf("Found data %s\n", this->data);
}
this = this->next;
}
}
And I have this in main (contains is called on the last line):
NODE *head;
head = malloc(sizeof(NODE));
bool headNode = true;
char userID[1000];
char userIDsearch[180];
char test[180] = "monkey";
while((fgets(userID,1000,stdin) != NULL)){
// printf("%s\n", userID);
if(headNode == true)
{
head = insert(NULL, userID);
headNode = false; //this is used to insert data to my linked list for the first time
}
else
{
head = insert(head, userID);
}
}
contains(head, test);
strcmp
should be giving zero if I input "monkey", but it gives 1. Also, I tested and used strlen
on both strings I am comparing, for some reason strlen
gives length + 1 for temp
(my input), but strlen
gives the correct length for ~user` (which I set to the string "monkey").
Don't forget that fgets()
retains the newline, but you did not remove it, or add one to the end of test
.
You would spot this if you printed the input using a statement such as:
printf("User ID <<%s>>\n", userID);
inside the loop. The <<
and >>
show you where the string starts and ends, and would reveal the embedded newline.
这篇关于strcmp不给0,但是两个参数是一样的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!