2012-04-17 61 views
0

我得到一個「字符串不可忽略」的錯誤代碼,它幾乎是從互聯網上某處複製的。應用程序在發佈模式下完美編譯(VS 2010),但在調試模式下不斷拋出錯誤。它應該將字符串拆分爲*並將每個單詞保存爲一個向量。有沒有人有任何想法?它似乎並不喜歡比較中的(string :: npos!= found)部分。C++ Tokenize字符串不可忽略

string newString = "Something*NotCool"; 

size_t found = newString.find_first_of("+*-/%()"); 
size_t lastPos = 0; 
//while (found != newString.length) 
while (string::npos != found || string::npos != lastPos) 
{ 
    if (found >= newString.length()) break; 
    if (found == lastPos) 
    { 
     lastPos = found+1; 
     found = newString.find_first_of("+*-/()", found+1); 
    } 
    string temp (newString,lastPos,found); 
    temp.assign(newString, lastPos, found-lastPos); 
    strings.push_back(temp); 
    lastPos = found+1; 
    found = newString.find_first_of("+*-/()", found + 1); 
} 

您的幫助表示感謝!

+0

它編譯我使用VS 2010的(我用的CL,而不是IDE)。你將需要顯示更多的代碼。 – 2012-04-17 22:51:30

+0

你確定這是引發錯誤的代碼嗎?我懷疑這是添加了一些東西來避免錯誤信息的代碼,但是它仍然存在最後一個字不會添加到'strings'的問題。另外,請注意編譯器錯誤和運行時錯誤之間的區別 - 它們完全不同,並且說'完​​美編譯'與說它運行沒有錯誤消息(這與說正確運行不同)不同。 – 2012-04-17 22:56:38

+0

我想你的'if(found == lastPos)'邏輯是關閉的。這似乎試圖檢測一行中有兩個* s,並忽略它們。但是,連續3個或更多*不會被捕獲。 – Lalaland 2012-04-17 22:58:02

回答

1

你的代碼在VS2010中對我沒有任何錯誤。

既然你就可以訪問正則表達式(<regex>庫),另一種選擇可能是:

std::string str = "Something*NotCool"; 
std::regex re("[^(\\*\\+%/\\-\\(\\))]+"); 
std::sregex_token_iterator begin(str.begin(), str.end(), re), end; 
std::vector<std::string> tokens; 
std::copy(begin, end, std::back_inserter(tokens)); 
+0

這是EPIC。非常感謝你的幫助。我只是在re(...)中添加了一個\\ /以確保它處理分隔符號(我希望我做到了這一點 - 這是一種臨時測試)。看起來我有一些閱讀這些「新」功能。再次感謝! – 2012-04-17 23:22:48

+0

我喜歡如何逃避正則表達式逃脫,使它爆炸成有點迷人的東西。這是它自己的小「沃爾多在哪裏?」對於分隔符字符集。別忘了''%''不應該總是在那裏(或者這可能是原代碼中的另一個錯誤......) – 2012-04-17 23:41:40

+2

@MichaelBurr:這可能是爲什麼C++ 11引入了原始字符串文字。 – 2012-04-17 23:46:57