C++:如何使用 STL 逐行迭代 std::string 中的文本?
我在 std::string 对象中有一个文本。文本由几行组成。我想使用 STL(或 Boost)逐行迭代文本。我想出的所有解决方案似乎都远非优雅。我最好的方法是在换行符处分割文本。有更优雅的解决方案吗?
更新:这就是我一直在寻找的:
std::string input;
// get input ...
std::istringstream stream(input);
std::string line;
while (std::getline(stream, line)) {
std::cout << line << std::endl;
}
I have a text in a std::string object. The text consists of several lines. I want to iterate over the text line by line using STL (or Boost). All solutions I come up with seem to be far from elegant. My best approach is to split the text at the line breaks. Is there a more elegant solution?
UPDATE: This is what I was looking for:
std::string input;
// get input ...
std::istringstream stream(input);
std::string line;
while (std::getline(stream, line)) {
std::cout << line << std::endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么将文本保留在源文件中?将其保存在单独的文本文件中。使用 std::ifstream 打开它并使用
while(getline(...))
迭代它。或者,如果文本必须位于
std::string
变量中以类似的方式使用std::istringstream
逐行读取如果您的问题是如何在不使用 + 的情况下按词法将文本放入代码中,请注意,相邻的字符串文字在编译之前已连接,因此您可以这样做:
Why do you keep the text in your source file? Keep it in a separate text file. Open it with std::ifstream and iterate over it with
while(getline(...))
Alternatively, if the text HAS to be in a
std::string
variable read line by line usingstd::istringstream
in a similar mannerIf your question is how to put the text lexially into your code without using +, please note that adjacent string literals are concatenated before compilation, so you could do this:
使用 Boost.Tokenizer:
prints
请注意,它会跳过空行,这可能会导致或者可能不是你想要的。
Use Boost.Tokenizer:
prints
Note that it skips over empty lines, which may or may not be what you want.
如果您想逐行循环,正如您所说,为什么在换行符处分割文本不正是您想要的?
您没有发布代码来显示您是如何做到这一点的,但您的方法似乎正确地完成了您所说的目标。为什么会感觉低人一等?
If you want to loop
line by line
, as you say, why would splitting the text at line breaks not be exactly what you want?You didn't post code showing how you're doing it, but your approach seems correct to accomplish what you said you wanted. Why does it feel inferior?