Originally Posted by
yodaliketaco
This function is causing the program to crash, but I can't spot my error.
Code:
string removeSpaces (string input)
{
string output;
int n;
int o = 0;
for ( n = 0; n < (int)input.length(); n++ )
{
if (input[n] != ' ')
{
output[o] = input[n];
o++;
}
}
return output;
}
Any ideas for what is wrong with the function?
There are a few things which could be causing this, first you can't use strings like this:
Code:
output[o] = input[n];
Use the member string::at, like this:
Code:
if(foo.at(bar) == 'foobar'){
foo.at(bar) = foobar.at(bar);
}
And why are you manually checking for spaces? The string class has a member (find) who searches and returns the position of a character or string inside the string.
Code:
if( foo.find(' ') != std::string::npos ){ // if it's found
foo.at( foo.find(' ') ) = '_'; // replace a space with an underscore
}