stricmp不起作用

shi*_*bar 1 c++ visual-studio-2010

我在特定功能中使用stricmp有问题,在其他功能中,除此功能外,它都能正常工作。问题是,即使它比较相同的字符串(char *),也不会返回0。这可能是什么问题?(很抱歉,我会尝试对其进行格式化)是以下代码:

Employee* CityCouncil::FindEmp(list<Employee*> *lst, char* id)  
{  
 bool continue1 = true;  
 Employee* tmp= NULL;  
 char* tmpId = NULL, *tmpId2 = NULL;  
 list<Employee*>::iterator iter = lst->begin();  
 if ((id == NULL) || (lst->empty()==true))  
  return NULL;  
 while ((iter != lst->end()) && (continue1)){  
  tmp = (Employee*)(*iter);  
  tmpId = (*tmp).GetId();  
  if(tmpId != NULL)  
  {  
      if(stricmp(tmpId,id) == 0)  
       continue1 = false;  
  }  
  if (continue1 == true)  
  iter++;  
 }  
 if (iter == lst->end())
     return NULL;
 return (Employee*)(*iter);
}
Run Code Online (Sandbox Code Playgroud)

And*_*Dog 5

永远不要责怪属于C库的函数。stricmp当然可以按预期工作,这意味着字符串确实不同。此函数的逻辑肯定有问题-您应该使用printf语句找出字符串在何处以及为何不同的原因。

编辑:我整理了一个简单的测试程序。这对我有用:

#include <stdio.h>
#include <list>
using namespace std;

// Dummy
class Employee
{
    public:
        Employee(const char *n){ id = strdup(n); }
        char *id;
        char *GetId() { return this->id; }
};

Employee* FindEmp(list<Employee*> *lst, char* id)
{
    bool continue1 = true;
    Employee *tmp = NULL;
    char* tmpId = NULL;

    list<Employee*>::iterator iter = lst->begin();
    if(id == NULL || lst->empty())
        return NULL;

    while(iter != lst->end() && continue1)
    {
        tmp = (Employee*)(*iter);
        tmpId = (*tmp).GetId();
        if(tmpId != NULL)
        {
            if(stricmp(tmpId,id) == 0)
                continue1 = false;
        }
        if(continue1 == true)
            iter++;
    }

    if(iter == lst->end())
        return NULL;

    return (Employee*)(*iter);
}


int main(int argc, char **argv)
{
    list<Employee*> l;

    l.push_back(new Employee("Dave"));
    l.push_back(new Employee("Andy"));
    l.push_back(new Employee("Snoopie"));

    printf("%s found\n", FindEmp(&l, "dave")->GetId());
    printf("%s found\n", FindEmp(&l, "andy")->GetId());
    printf("%s found\n", FindEmp(&l, "SnoOpiE")->GetId());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了您提供的功能。同样,stricmp没错,问题一定出在您的代码中。