大家好,我正在编写一个自动换行函数来格式化 C++ 中的控制台文本。我的问题是 A)我不完全了解 std::string::iterators 做什么,或者 B)我的一个迭代器没有正确设置。任何人都可以阐明此代码失败的原因吗?
顺便说一句:对不起,如果这太详细了。我不确定大多数程序员(我是“新手”)是否在他们的机器上安装了 C++ 编译器。
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;
}
我没有得到正确的输出。假设我这样称呼它:
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;
我得到了不满意的输出:
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 . . .
我的问题是我在不合适时收到换行符。我经常收到换行符,我没有看到任何明显的错误说明为什么会这样。我希望独立的人(我在这个算法上花了几个小时,没有正确的结果是非常令人沮丧的)可以看看这个问题。另外,有什么明显的优化技巧吗?