title: How do you wrap text at a space in C++
body: <p>I'm trying to make a text wrapping function that will receive a string and an amount of characters to count over before wrapping. If possible, I would like to keep any words from being cut off by looking for the previous space and wrapping there.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstddef&gt;
  #include &lt;string&gt;
  using namespace std;
  
  string textWrap(string str, int chars) {
  string end = "\n";
  
  int charTotal = str.length();
  while (charTotal&gt;0) {
      if (str.at(chars) == ' ') {
          str.replace(chars, 1, end);
      }
      else {
          str.replace(str.rfind(' ',chars), 1, end);
      }
      charTotal -= chars; 
  }
  return str;
  }
  
  int main()
  {
      //function call
      cout &lt;&lt; textWrap("I want to wrap this text after about 15 characters please.", 15);
      return 0;
  }
  </code></pre>