split function for strings!

#include <iostream>
#include <string>
using namespace std;

string split (string str, char c)
{
string ret;
for(int i=0 ; i <= str.length() ; i++)
{
if (str[i] == c)
{
break;
}
ret[i] = str[i];
}
return ret;
}
int main()
{
string str = "My name is Shehio, and I have 18 years.";
string out = split(str, ',');
cout <<str << endl << out;
return 0;
}
// produces a runtime error that I can't figure out! any help please
You try to access the individual characters in ret, but the problem is there are none.

std::strings are not like character arrays where all of the characters are pre-allocated; std::strings start at length 0. So, using the [] operator will throw a runtime error because the character you're telling the string to change doesn't exist yet.

Use std::string.append to append characters to the end of the string. (The += operator works as well).
Also your for loop should use less-than (<) instead of less-than-or-equal (<=) otherwise you might run off the end of your string. In this case you don't actually get to the end of the string because the loop terminates when you get to the comma, but if you entered a character that wasn't in the string, it would run off the end.
Topic archived. No new replies allowed.