2011-01-11 37 views
0

我再次对以下一个strage C++的事:查找字符串返回一个子-1虽然子可用

被一个进来的线(string.c_str())>变为线
POS是从哪里开始搜索
小号是一个字符串的位置(string.c_str())来寻找>变得命令

它一切正常,直到命令是“-1”。在这种情况下,虽然行包含它,但字符串“-1”未找到。 我错过了什么?

代码:

bool Converter::commandAvailable(const char* l, int pos, const char* s) { 

string line = l; 
string command = s; 
int x = line.find(command, pos); 
if (x != -1) { 
    return true; 
} 
return false; 
} 

提前感谢!

+0

你确信你通过在`为const char * l`,无疑指出了一些数据,在它“-1”?既然你传递`l`的const char *`,我想知道在你传递给你的函数之前,你是不是意外地将这个指针超越了你的“-1”,也许在你的代码的其他地方? – BeeBand 2011-01-11 11:20:53

+2

std :: string :: find返回一个size_t,你应该和std :: string :: npos – stijn 2011-01-11 11:35:01

回答

2

这会帮助你找到问题:

bool Converter::commandAvailable(const char* l, int pos, const char* s) 
{ 
    string line = l; 
    string command = s; 
    std::cout << "INPUT" << std::endl; 
    std::cout << "LINE: " << line << std::endl; 
    std::cout << "CMD: " << command << std::endl; 
    std::cout << "START: " << pos << std::endl << std::endl; 

    std::size_t x = line.find(command, pos); 

    std::cout << "OUTPUT: " << x << std::endl; 
    if (x != std::string::npos) 
    { 
     return true; 
    } 
    return false; 
} 
相关问题