2016-10-30 67 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“在树林里”并且在声明的数组之后用任何东西标记。