如何在 getline() 中不使用 作为分隔符

How to NOT use as delimiter in getline()

本文关键字:分隔符 getline      更新时间:2023-10-16

我正在尝试从纯文本文件中读取行,但是句子中间有换行符,因此getline()读取直到换行符以及直到句点。文本文件如下所示:

then he come tiptoeing down and stood right between us. we could
a touched him nearly. well likely it was minutes and minutes that
there warnt a sound and we all there so close together. there was a
place on my ankle that got to itching but i dasnt scratch it.

我的读入代码:

  // read in sentences
  while (file)
  {
    string s, record;
    if (!getline( file, s )) break;
    istringstream ss(s);
    while (ss)
    {
      string s;
      if (!getline(ss, s, '.')) break;
          record = s;
      if(record[0] == ' ')
          record.erase(record.begin());
      sentences.push_back(record);
    }
  }
  // output sentences
  for (vector<string>::size_type i = 0; i < sentences.size(); i++)
    cout << sentences[i] << "[][][][]" << endl;
[ ][ ]

[ ][ ] 的目的是检查换行符是否用作分隔符,而不仅仅是读入字符串。输出如下所示:

then he come tiptoeing down and stood right between us.[][][][]
we could[][][][]
a touched him nearly.[][][][]
well likely it was minutes and minutes that[][][][]
there warnt a sound and we all there so close together.[][][][]
there was a[][][][]
place on my ankle that got to itching but i dasnt scratch it.[][][][]

你的问题到底是什么?

您使用getline()通过换行符从file流中读取,然后使用 istringstream is 和分隔符'.' getline()解析该行。 所以当然,你会在新行和'.'上都弄断你的弦。

getdelim() 的工作方式与 getline() 类似,不同之处在于可以将换行符以外的行分隔符指定为 delimiter 参数。 与 getline() 一样,如果在到达文件末尾之前输入中不存在分隔符,则不会添加分隔符。

ssize_t getdelim(char **restrict lineptr, size_t *restrict n, int delimiter, FILE *restrict stream);