2016-10-30 65 views
3

我想在C++中使用strtok來獲取一個字符串的標記。但是,我發現在5次運行中,由函數返回的令牌不正確。有人可以問,建議可能是什麼問題?Strtok在C++異常行爲

示例代碼複製我所面臨的問題:

#include<iostream> 
#include<vector> 
#include<cstring> 

using namespace std; 
#define DEBUG(x) cout<<x<<endl; 


void split(const string &s, const char* delim, vector<string> & v) 
{ 
     DEBUG("Input string to split:"<<s); 

     // to avoid modifying original string first duplicate the original string and return a char pointer then free the memory 
     char * dup = strdup(s.c_str()); 
     DEBUG("dup is:"<<dup); 
     int i=0; 
     char* token = strtok(dup,delim); 

     while(token != NULL) 
     { 
       DEBUG("token is:"<<string(token)); 
       v.push_back(string(token)); 
       // the call is treated as a subsequent calls to strtok: 
       // the function continues from where it left in previous invocation 
       token = strtok(NULL,delim); 
     } 
     free(dup); 
} 

int main() 
{ 
     string a ="MOVC R1,R1,#434"; 

     vector<string> tokens; 
     char delims[] = {' ',','}; 
     split(a,delims,tokens); 
     return 0; 
} 

輸出示例:

[email protected]:~/Documents/practice$ ./a.out 
Input string to split:MOVC R1,R1,#434 
dup is:MOVC R1,R1,#434 
token is:MOVC 
token is:R1 
token is:R1 
token is:#434 

[email protected]:~/Documents/practice$ ./a.out 
Input string to split:MOVC R1,R1,#434 
dup is:MOVC R1,R1,#434 
token is:MO 
token is:C 
token is:R1 
token is:R1 
token is:#434 

正如你在第二輪看到創建的令牌是MO C R1 R1 #434而不是MOVC R1 R1 #434

我也嘗試過檢查庫代碼,但無法找出錯誤。請幫忙。

EDIT1:我的gcc版本是:gcc version 6.2.0 20161005 (Ubuntu 6.2.0-5ubuntu12)

+2

'strtok()'是您可以選擇的最差技術之一。 –

+0

你能推薦任何其他方法嗎?我想用多個分隔符分割字符串。另外,我不想使用boost庫。 –

+1

這裏有一些方向:http://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it –

回答

8
char delims[] = {' ',','}; 

應該

char delims[] = " ,"; 

你傳遞字符的列表,而不是一個char *軸承分隔符使用的名單,因此意外行爲,因爲strtok需要以0結尾的字符串。在你的情況下,strtok「在樹林裏」並且在聲明的數組之後用任何東西標記。