0

Is there some kind of problem with this function as I have tried displacing each command but it still shows segmentation error

string splitSentence(string str)
    {
        string appendedWords{""},xx;
        for(int i=0 ; i < str.length();i++)
        {
            xx = str[i];
            if (xx == " ")
            {
                
                appendedWords = "";
            }
            else 
            {
                appendedWords = appendedWords + xx;
                
            }        
        }
    }
tadman
  • 208,517
  • 23
  • 234
  • 262
Reaper
  • 1
  • Tip: Don't forget that `x = x + y` is often better written as `x += y`. – tadman Apr 29 '21 at 09:04
  • 7
    There is no `return` statement even though function is declared to return a `string`. – user7860670 Apr 29 '21 at 09:04
  • 1
    Are you trying to solve [this problem](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string)? – tadman Apr 29 '21 at 09:04
  • 3
    Turn on all compiler warnings, or actually read the compiler warnings that you ignored. Even better, tell your compiler to treat warnings as errors so that you are forced to read them. – paddy Apr 29 '21 at 09:34

1 Answers1

0

I don't know exactly what your program should do, because now it only finds the last word in your string.

I just summarized the comments and improved your code a little bit. Code

Changed parts:

  1. pass Strings by reference

  2. str.length() returns an unsigned integer whilst you were using an integer, this caused a compiler warning

  3. used x+=y instead of x = x + y as tadman pointed out

  4. added return statement

Bananenkönig
  • 547
  • 4
  • 12