使用C++逐行读取字符串

51

我有一个包含多行的 std::string,我需要逐行读取它。请给我展示一个简单的例子。

例如:我有一个字符串 string h;

h 将是:

Hello there.
How are you today?
I am fine, thank you.

我需要以某种方式提取出 Hello there., How are you today?, 和 I am fine, thank you.


当你说“multiple link”时,你是真的指它,还是你想说“lines”? - Petruza
请查看FAQ中“我该如何在这里提问?”部分的最后一段。 - tenfour
5个回答

92
#include <sstream>
#include <iostream>

int main() {
    std::istringstream f("line1\nline2\nline3");
    std::string line;    
    while (std::getline(f, line)) {
        std::cout << line << std::endl;
    }
}

11

有几种方法可以实现这个功能。

你可以在循环中使用 std::string::find 查找 '\n' 字符并在位置之间使用 substr() 函数。

你可以使用 std::istringstreamstd::getline( istr, line )(可能是最简单的方法)。

你可以使用 boost::tokenize


5

“cplusplus.com”有很多错误(尽管我在那个页面上看不到任何明显的错误),使用全局的std::getline更好,这样你就可以使用std::string - Lightness Races in Orbit

0

如果您不想使用流:

int main() {
  string out = "line1\nline2\nline3";
  size_t start = 0;
  size_t end;
  while (1) {
    string this_line;
    if ((end = out.find("\n", start)) == string::npos) {
      if (!(this_line = out.substr(start)).empty()) {
        printf("%s\n", this_line.c_str());
      }

      break;
    }

    this_line = out.substr(start, end - start);
    printf("%s\n", this_line.c_str());
    start = end + 1;
  }
}

1
流(Streams)确实更容易,但有时您可能有一个编码标准,不允许使用流 :) - ericcurtin

0

我在寻找一个标准实现函数,它可以从字符串中返回特定的行。我遇到了这个问题,并且被接受的答案所帮助。我也有自己的实现想要分享:

// CODE: A
std::string getLine(const std::string& str, int line)
{
    size_t pos = 0;
    if (line < 0)
        return std::string();

    while ((line-- > 0) and (pos < str.length()))
        pos = str.find("\n", pos) + 1;
    if (pos >= str.length())
        return std::string();
    size_t end = str.find("\n", pos);
    return str.substr(pos, (end == std::string::npos ? std::string::npos : (end - pos + 1)));
}

但是我已经把自己的实现替换成了被接受答案中所展示的那个,因为它使用标准函数且更少容易出错。

// CODE: B
std::string getLine(const std::string& str, int lineNo)
{
    std::string line;
    std::istringstream stream(str);
    while (lineNo-- >= 0)
        std::getline(stream, line);
    return line;
}

这两个实现之间存在行为差异。CODE: B会从每个返回的行中删除换行符。CODE: A不会删除换行符。

我发布我的答案到这个不活跃问题的意图是让其他人看到可能的实现。

注意:

我不想进行任何优化,而是想在黑客马拉松中完成给我的任务!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接