【发布时间】:2019-10-09 22:10:28
【问题描述】:
我需要多行字符串,然后在前面加上空格。
我正在使用 boost::split 拆分字符串并将值分配给向量。然后在 for-each 循环中,我在向量值中添加空格。
static string test(){
std::string text = "This is a sentence.\nAnd another sentence";
string nl = "\n";
string pad=" ";
string txt;
std::vector<std::string> results;
boost::split(results, text, boost::is_any_of(nl));
for(string line : results){
txt = pad + line + nl;
cout << txt;
}
return txt;
}
我应该得到如下返回值。 cout结果正确但无法获取返回值txt。
This is a sentence.
And another sentence
【问题讨论】:
-
你得到了什么?
-
我建议你对你的代码做一些rubber duck debugging,尤其是你有的那个循环。
-
您的代码在每次循环迭代时重新初始化
txt,将其分配为一个整体。试试txt.append(pad + line + nl)。 -
我认为要让人们真正理解他们的错误,我们应该停止在零时间内为这类问题提供解决方案。我们应该让 OP 去阅读和思考像 Steve 和 Someprogrammer dude 那样的 cmets。