我在特定功能中使用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);
}
答案 0 :(得分: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;
}
请注意,我使用了您提供的功能。同样,stricmp没有任何问题,问题必须出在你的代码中。
答案 1 :(得分:1)
您的代码看起来正确;也许你没有传递你认为自己的弦乐,或者内存会以某种方式被破坏?
但是,您的功能可以写得更清晰。
// Why is this a method off of CityCouncil? As written, it
// doesn't use any CityCouncil members.
//
// Also, why not pass lst by reference? Like this:
// Employee* CityCoucil::FindEmp(list<Employee*>& lst, char *id) { ...
//
// Also, const correctness is a good idea, but that's more complicated.
// Start with this:
// Employee* CityCoucil::FindEmp(const list<Employee*>& lst, const char *id) { ...
//
// Also, it's easy to leak memory when using a list of pointers, but that's
// another topic.
Employee* CityCouncil::FindEmp(list<Employee*> *lst, char* id)
{
// No need for continue1; we'll use an early return instead;
// No need for tmp, tmpId, tmpId2; just call methods directly
// off of iter.
if (id == NULL || lst->empty())
return NULL;
// You should NOT do a C-style "(Employee*)" cast on *iter.
// C-style casts are generally to be avoided, and in this case,
// it shouldn't be necessary.
// Use a for loop to simplify your assigning iter and incrementing it.
for (list<Employee*>::iterator iter = lst->begin(); iter != list->end(); iter++) {
if ((*iter)->GetId()) {
if (stricmp((*iter)->GetId(), id) == 0) {
return *iter;
}
}
}
return NULL;
}