我试图从一个纯文本文件中读入行,但是句子中间有换行符,所以 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/