大概在两年前, 我踩了一次strtok的坑, 并在博文中做了记录, 永远不要用strtok, 最近再次遇到此坑, 先不多说。 我来教你用恶心的strtok函数来恶意修改const string &str 中的str:
#include <string>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int Str2Vector(const string& str, vector<string> &v, const char *p)
{
v.clear();
char *pTmp = strtok(const_cast<char *>(str.c_str()), p);
while(NULL != pTmp)
{
v.push_back(pTmp);
pTmp = strtok(NULL, p);
}
return v.size();
}
int main()
{
string s = "|ab|cd|efg|h|";
string t = s;
vector<string> v;
Str2Vector(s, v, "|");
for(vector<string>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << *it << endl;
}
cout << s << endl;
cout << t << endl;
return 0;
}
结果:
taoge@localhost Desktop> g++ main.cpp
taoge@localhost Desktop> ./a.out
ab
cd
efg
h
|abcdefgh
|abcdefgh
taoge@localhost Desktop>
我们看到, 调用Str2Vector后, s的值居然就改变了, 更为奇葩的是,t的值也改变了。 把const string &str中的&去掉, 结果也一样。
为什么会这样呢? 因为strtok很恶心, 有兴趣的朋友随便在网上一搜, 对strtok的骂声一片啊。
还有人说: 是你自己不会用strtok. 我要说: 少装逼。
在下面博文中, 我会继续对strtok口诛笔伐。