Note that there are some explanatory texts on larger screens.

plurals
  1. POwordwrap function
    primarykey
    data
    text
    <p>Hey guys, I'm writing a word wrap function to format console text in C++. My problem is either A) I don't understand exactly what std::string::iterators do, or B) one of my iterators is not being set properly. Can anyone shed some light on the reason this code fails?</p> <p>by the way: sorry if this goes into too much detail. I'm not sure if most programmers (I'm a "newbie") have a C++ compiler installed on their machine. </p> <pre><code>std::string wordWrap(std::string sentence, int width) { //this iterator is used to optimize code; could use array indice //iterates through sentence till end std::string::iterator it = sentence.begin(); //this iterator = it when you reach a space; will place a newline here //if you reach width; std::string::iterator lastSpace = sentence.begin(); int distanceToWidth = 0; while (it != sentence.end()) { while (it != sentence.end() &amp;&amp; distanceToWidth &lt; width) { if (*it == ' ') { lastSpace = it; } distanceToWidth++; it++; } distanceToLength = 0; *lastSpace = '\n'; //skip the space if (it != sentence.end()) { it++; } } return sentence; } </code></pre> <p>I'm not getting correct output. Assuming I called it like this:</p> <pre><code>std::cout &lt;&lt; wordWrap("a b c abcde abcdef longword shtwd", 5) &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; wordWrap("this is a sentence of massive proportions", 4) &lt;&lt; std::endl; </code></pre> <p>I get unsatisfying output of this:</p> <pre><code>a b c abcde abcdef longword shtwd //yes I get his, instead of this his is a sentence of massive proportions Press any key to continue . . . </code></pre> <p>My problem is that I'm am getting newlines when inappropiate. I am getting newlines too often, and I don't see any obvious error as to why that is. I was hoping someone independent (I've spent a few hours on this algorithm, and to not have the right results is quite frusturating) of the problem could look at it. Also, any obvious optimization tips? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload