我正在嘗試使用strtok(),但它給出了分段錯誤。任何人都可以告訴我代碼中的問題在哪裏,並且有沒有更好的方法來標記strtok()以外的字符串?在C++中標記字符串的最佳方法是什麼?
void tokenize(char *tagToFind, char *record, char *delim)
{
char *token;
char *itr;
char *tag;
char *tag5;
int toBreak=0;
token = strtok(record,delim);
while (token != NULL)
{
itr = token;
while (*itr != '{')
{
tag = itr;
itr++;
tag++;
}
tag = '\0';
if ((strcmp(tag, tagToFind) == 0))
break;
else
token = strtok(NULL,delim);
}
if(strcmp(tag5, "tag5") == 0)
{
cout<<"\n\n\n\n\t\ttag5 is present.";
}
}
int main()
{
char *tag = "tag5";
char *record = "tag1{0}|tag2{0}|tag3{0}|tag4{0}|tag5{tag51{0};tag52{0};tag53{0};tag54{0};tag55{tag551{0}:tag552{0}:tag553{0}:tag554{0}:tag555{0}}}";
char *delim = "|";
tokenize(tag, record, delim);
return 0;
}
http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – sujin
這是C還是C++?如果是後者,那麼你應該檢查std :: string – olevegard
分段錯誤是因爲你正在修改'record'指向的字符串文字。 'strtok()'修改第一個參數讀取[strtok導致段錯誤,但不通過代碼時](http://stackoverflow.com/questions/17551665/strtok-causing-segfault-but-not-when-step-through-code/17551779#17551779) –