嗨,大家好,我正在編寫一個單詞封裝函數來格式化C++中的控制檯文本。我的問題是要麼A)我不明白什麼std :: string :: iterators做,或B)我的一個迭代器沒有正確設置。任何人都可以闡明這個代碼失敗的原因嗎?順便說一句:對不起,如果這太詳細了。我不確定大多數程序員(我是「新手」)是否在他們的機器上安裝了C++編譯器。wordwrap函數
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 . . .
我的問題是,我正在逐漸換行符時不合格的。我越來越頻繁地使用換行符,並且我沒有看到任何明顯的錯誤。我希望有人獨立(我已經花了幾個小時的時間在這個算法上,並且沒有得到正確的結果很令人沮喪),可以看看它。另外,任何明顯的優化技巧?
不,這個問題是範圍特定於我的問題與迭代器。就解決輸出的算法而言,你的回答並不能幫助我。儘管如果您需要,隨時可以關閉此功能,但現在我已經得到了我的答案。 – jkeys 2009-07-05 06:40:36