ラッピングする前に文字列と文字数を受け取るテキストラッピング関数を作成しようとしています。可能であれば、前のスペースを探してそこにラッピングすることによって、言葉が途切れないようにしたいと思います。どのように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