2011-01-11 71 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; 
}