Function with Strings Confusion

I'm writing a function to trim leading and trailing white space from a string. It should leave any blanks there in the middle. Unfortunately the program crashes when I run it, and I'm not sure why.

string trim(string s)
{
char c = ' ';
string temp;

for(int i = 0; i < s.length(); i++)
{

if(s.at(i) != c)
{
temp = temp + s.substr(i, 1);
}

if(s.at(i) == c and s.at(i + 1) != c and s.at(i - 1) != c)
{
temp = temp + s.substr(i, 1);
}



}


return (temp);

}
if(s.at(i) == c and s.at(i + 1) != c and s.at(i - 1) != c)

If 'i' is zero... i - 1 will be out of bounds.

If 'i' is equal to length-1... then i+1 will be out of bounds.


Both of these will happen because you are looping from 0 to length.

Since you are calling at(), an out of bounds index will throw an exception... which...since you aren't catching it... will cause the program to crash.
Thanks so much, I've gotta pay attention to these things!
Topic archived. No new replies allowed.