我试图制作一个文本包装函数,它将在包装之前接收一个字符串和一定数量的字符。如果可能的话,我想通过查找以前的空间并包裹在那里来阻止任何词语被切断。如何在C++空间中包装文本
#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
string textWrap(string str, int chars) {
string end = "\n";
int charTotal = str.length();
while (charTotal>0) {
if (str.at(chars) == ' ') {
str.replace(chars, 1, end);
}
else {
str.replace(str.rfind(' ',chars), 1, end);
}
charTotal -= chars;
}
return str;
}
int main()
{
//function call
cout << textWrap("I want to wrap this text after about 15 characters please.", 15);
return 0;
}
你对现有的代码有什么疑问?它不起作用吗?如果是这样,它是如何失败的? – LThode