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?
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.
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() && distanceToWidth < width)
{
if (*it == ' ')
{
lastSpace = it;
}
distanceToWidth++;
it++;
}
distanceToLength = 0;
*lastSpace = '\n';
//skip the space
if (it != sentence.end())
{
it++;
}
}
return sentence;
}
I’m not getting correct output. Assuming I called it like this:
std::cout << wordWrap("a b c abcde abcdef longword shtwd", 5) << std::endl << std::endl;
std::cout << wordWrap("this is a sentence of massive proportions", 4) << std::endl;
I get unsatisfying output of this:
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 . . .
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?
The problem is that the word this is 4 characters, and you are wrapping at four characters. So it is trying to wrap before it has set lastSpace to something reasonable.
Look at it from the point of stepping through the code:
ETC
Thus we output an extra newline instead of the “t” in “this”
about fixing it… well… you can figure it out