2

I cant seem to return str in my RemSpacePunct function.

I wanted to make a function that removes spaces in a string but when I run the code, it won't remove the space.

string RemSpacePunct(string str);
string sort(string str);

int main(){ 
    string s = "partial men";
    
    sort(s.begin(), s.end());
    
    RemSpacePunct(s);   
    cout << s;  
}

string RemSpacePunct(string str)
{
    //add code here
    int s, i;
    
    s = str.length();
    
    for(i = 0; i < s; i++){
        if(isalnum(str[i]) == false){
            str.erase(i, 1);
        }       
    }   
    return str;
}
3
  • 5
    You are ignoring the return value when you call the function: s = RemSpacePunct(s); Commented Jan 25, 2021 at 12:27
  • When you call RemSpacePunct(s);, you should not expect this to have any effect on the value of s within the function, no matter what code you write in the function body. This is because you have passed the string by value - making a copy - and are expecting to receive the changes using the return value, but you do nothing with that return value. Commented Jan 25, 2021 at 12:28
  • 2
    Sidenote: You will go out of bounds at some point, because but you iterate from 0 to the original length of str and don't take into account that strs length decreases. Commented Jan 25, 2021 at 12:31

1 Answer 1

3

You're ignoring the return value. str is copied when it's passed to the function, so any modifications you perform on the argument aren't reflected back to the original value. Instead, you should return a modified value - which you do, but you then ignore it instead of using it:

string result = RemSpacePunct(s);   
cout << result;  
Sign up to request clarification or add additional context in comments.

1 Comment

Or use pass-by-reference to save the value. It is not clear what the real intention is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.