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

时间:2014-02-26 06:23:58

标签: c++

我正在尝试从纯文本文件中读取行,但在句子中间有换行符,因此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.[][][][]

2 个答案:

答案 0 :(得分:1)

你的问题究竟是什么?

您正在使用getline()使用换行符分隔符从file流中读取,然后使用getline()和分隔符{{istringstream is解析该行1}}。所以当然你在新行和'.'上都会破坏你的字符串。

答案 1 :(得分:0)

  

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

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