I could debug it for you, I guess but that won't help you in the long run. Here's what you do.
After every line, put a printf() or cout staement dumping the changed variables to standard output. Then run your code, passing a simple set of parameters to it:
vector<string> x = split ("Hello there, Bob.", ' ');
Then, examine the output to see why your implementation isn't working. You'll probably have to break out of the code since, if it's just sitting there, you've probably got yourself one of those new-fangled infinite loops.
Give a man a fish and he'll eat for a day, teach a man to fish, he'll never be hungry again.
Or the Terry Pratchett version:
Give a man some fire and he'll be warm for a day, set a man on fire, he'll be warm for the rest of his life.
Update:
Since you've stated that you've actually done what I suggested, here's what I found out from doing it. It's evident that when you set beg
to temp
at the end of the while
loop, it's pointing at the space. That was discovered by printing the beg
string at the top of the while
loop - it never changed after the first word was extracted.
Then, when you do the next find
, it finds that exact same space rather than first skipping spaces then calling find
properly. You need to skip the spaces after each find
, making sure you don't iterate beyond the end of the string.
This is my solution. Use it as you wish.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> split( const string &str, const char &delim ) {
typedef string::const_iterator iter;
iter beg = str.begin();
vector<string> tokens;
while(beg != str.end()) {
//cout << ":" << beg._Myptr << ":" << endl;
iter temp = find(beg, str.end(), delim);
if(beg != str.end())
tokens.push_back(string(beg, temp));
beg = temp;
while ((beg != str.end()) && (*beg == delim))
beg++;
}
return tokens;
}
int main () {
vector<string> x = split ("Hello, my name is Bob. ", ' ');
return 0;
}
Without that space-skipping code at the end of the while
loop, the output was:
:Hello, my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
: my name is Bob. :
and so on, ad infinitum. With the skipping code, you get:
:Hello, my name is Bob. :
:my name is Bob. :
:name is Bob. :
:is Bob. :
:Bob. :