title: String Word Wrap in Message Box?
body: <p>I'm trying to wrap the words of a given string and display it in a message box using SFML (&lt;-- this doesn't matter ).</p>
  
  <p>So, what I am trying to do is to insert a new line before a word that is greater than the width of the message box. Here's the code:</p>
  
  <pre><code>string&amp; message::word_wrap( string&amp; msg , int w, int pt_size )
  {
      int text_width = w;
      vector&lt; string &gt; lines;
      string temp ( msg );
      temp += " ";
      int n = 0, p = 0;
  
      while ( n != -1 )
      {
          string substr;
          n = temp.find( " ", p+1 );
          if ( (n * pt_size) &gt;= text_width )
          {
              substr = temp.substr( 0, p );
              lines.push_back( substr );
              if ( n != -1 )
                  temp = temp.substr( p+1, string::npos );
              p = 0;
          }
  
          else p = n;
      }
  
      string rtn;
      for ( int i = 0; i &lt; lines.size(); i++ ) rtn += lines[i] + '\n';
      return rtn;
  }
  </code></pre>
  
  <p>I use it in my class like this:</p>
  
  <pre><code>message::message( sf::RenderWindow&amp; App, const string&amp; msg, int w, int h ) : app(App)
  {
      /* irrelevant code */
  
      string m = msg; // &lt;--
      m = this-&gt;word_wrap( m, w, text.GetSize() ); // &lt;--
      text.SetText(m);
  }
  </code></pre>
  
  <h2>There are two problems.</h2>
  
  <ol>
  <li>The algorithm wraps the words way before they exceed the width of
  the message box.</li>
  <li><p>The last few words are skipped for some reason, when I use
  it like this:</p>
  
  <pre><code>pro::message::display( App, "Hello World! Yada Yada Bla Bla Yda Yada Hehehe Hehe Hfmaf Heh last few words" );
  </code></pre></li>
  </ol>
  
  <p>It skips the last word, <em>words</em> :</p>
  
  <p><img src="https://i.stack.imgur.com/NPLbW.png" alt="last few words get skipped"></p>