kr*******@yahoo.com wrote:
I have a string that is delimited by commas. I'm using strtok and
putting the values in a vector. In some cases, I may have 2 commas side
by side and therefore need it to insert a null value. Right now, when
it encounters this it puts the next value in the vector and throws
everything else off. Does anyone know how I can insert a null value
when tokenizing a string?
Here is one I've worked up for this sort of task. If you need
strtok()'s ability to have multiple delimiters, then you'll have to
work it out yourself.
#include <vector>
#include <string>
#include <sstream>
using namespace std;
void Explode(const string &inString, vector<string> &outVector, char
separator)
{
stringstream inStream(inString);
string tempString;
while (getline(inStream, tempString, separator))
outVector.push_back(tempString);
}
int main()
{
string s = "one,two,three,,five";
vector<string> vec;
Explode (s, vec, ',');
for (int i = 0; i < vec.size(); i++)
cout << i << ": " << vec[i] << endl;
return 0;
}
Result:
0: one
1: two
2: three
3:
4: five
Brian