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

标签 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.[][][][]

最佳答案

您的问题到底是什么?

您正在使用 getline() 从带有换行符的 file 流中读取,然后使用 getline() 解析该行> 使用 istringstream is 和分隔符 '.'。因此,您当然会在换行符和 '.'.

处损坏字符串

关于c++ - 如何在 getline() 中不使用\n 作为分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033454/

相关文章:

c++ - 概念包含适用于函数,但不适用于结构

c++ - 如何在 C++ 中执行变量重载?

c++ - 变量未在此范围内声明 gcc 错误

c++ - 我怎样才能知道是否可以使用它使数组中的数字相等?

C++ 构建错误 - '{' 标记之前的预期类名|

C++ 类类型复制初始化

c++ - 为什么我必须声明一个静态 vector ?

c++ - 模板结构中枚举类的动态初始化

c++ - Wt泄漏内存吗?

c++ - 用条件 C++ 重复给定字符排列的算法