I’m trying to wrap the words of a given string and display it in a message box using SFML (<– this doesn’t matter ).
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:
string& message::word_wrap( string& msg , int w, int pt_size )
{
int text_width = w;
vector< string > lines;
string temp ( msg );
temp += " ";
int n = 0, p = 0;
while ( n != -1 )
{
string substr;
n = temp.find( " ", p+1 );
if ( (n * pt_size) >= 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 < lines.size(); i++ ) rtn += lines[i] + '\n';
return rtn;
}
I use it in my class like this:
message::message( sf::RenderWindow& App, const string& msg, int w, int h ) : app(App)
{
/* irrelevant code */
string m = msg; // <--
m = this->word_wrap( m, w, text.GetSize() ); // <--
text.SetText(m);
}
There are two problems.
- The algorithm wraps the words way before they exceed the width of
the message box. -
The last few words are skipped for some reason, when I use
it like this:pro::message::display( App, "Hello World! Yada Yada Bla Bla Yda Yada Hehehe Hehe Hfmaf Heh last few words" );
It skips the last word, words :

The easy solution is to make a copy of the string, and replace the space with a newline when appropriate.
The problem you are having, is because when you find the last space where you should to a linebreak, you still have text after that that is not pushed into the vector. You need to check if there are more text after the loop, and add that as a separate line.