title: Word Wrap Program C
body: <p>At the end of Chapter 1 of <em>The C Programming Language</em>, there are a few exercises to complete. The one I am doing now asks you to make a program that wraps a long string of text into multiple lines at a specific length. The following function works 100%, aside from the last line which does not get wrapped, no matter the specified maximum width of a line. </p>
  
  <pre><code>// wrap: take a long input line and wrap it into multiple lines
  void wrap(char s[], const int wrapline)
  {
      int i, k, wraploc, lastwrap;
  
      lastwrap = 0; // saves character index after most recent line wrap
      wraploc = 0; // used to find the location for next word wrap
  
      for (i = 0; s[i] != '\0'; ++i, ++wraploc) {
  
          if (wraploc &gt;= wrapline) {
              for (k = i; k &gt; 0; --k) {
                  // make sure word wrap doesn't overflow past maximum length
                  if (k - lastwrap &lt;= wrapline &amp;&amp; s[k] == ' ') {
                      s[k] = '\n';
                      lastwrap = k+1;
                      break;
                  }
              }
              wraploc = 0;
          }
  
      } // end main loop
  
      for (i = 0; i &lt; wrapline; ++i) printf(" ");
      printf("|\n");
      printf("%s\n", s);
  }
  </code></pre>
  
  <p>I have found the issue to be with the variable <code>wraploc</code>, which is incremented until it is greater than <code>wrapline</code> (the maximum index of a line). Once it is greater than <code>wrapline</code>, a newline is inserted at the appropriate location and <code>wraploc</code> is reset to 0. </p>
  
  <p>The problem is that on the last line, <code>wraploc</code> is never greater than <code>wrapline</code>, even when it should be. It increments perfectly throughout iteration of the string, until the last line. Take this example:</p>
  
  <pre><code>char s[] = "This is a sample string the last line will surely overflow";
  wrap(s, 15);
  </code></pre>
  
  <hr>
  
  <pre><code>$ ./a.out
                 |
  this is a
  sample string
  the last line
  will surely overflow
  </code></pre>
  
  <p>The line represents the location where it should be wrapped. In this case, <code>wraploc</code> has the value 14, when there are clearly more characters than that.</p>
  
  <p>I have no idea why this is happening, can someone help me out?</p>
  
  <p>(Also I'm a complete beginner to C and I have no experience with pointers so please stay away from those in your answers, thanks).</p>