Feb 14, 2014 at 9:05pm UTC
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);
}
Feb 14, 2014 at 9:45pm UTC
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.
Feb 15, 2014 at 4:04am UTC
Thanks so much, I've gotta pay attention to these things!