如何使用std :: copy从文件流直接读取到容器? [英] How can I use std::copy to read directly from a file stream to a container?
问题描述
我遇到了一个很酷的STL示例,该示例使用istream_iterators从std输入(cin)复制到向量.
I ran across a cool STL example that uses istream_iterators to copy from std input (cin) to a vector.
vector<string> col1;
copy(istream_iterator<string>(cin), istream_iterator<string>(),
back_inserter(col));
我将如何做类似的操作,将文件流直接读取到容器中?我们只说它是一个包含内容的简单文件:
How would I do something similar to read from a file-stream directly into a container? Let's just say its a simple file with contents:
敏捷的棕色狐狸跳过了懒狗."
"The quick brown fox jumped over the lazy dogs."
我希望每个单词在复制行之后成为向量中的单独元素.
I want each word to be a separate element in the vector after the copy line.
推荐答案
成功打开文件后,用文件流对象替换 cin
:
Replace cin
with file stream object after opening the file successfully:
ifstream file("file.txt");
copy(istream_iterator<string>(file), istream_iterator<string>(),
back_inserter(col));
实际上,您可以用任何C ++标准的 input 流替换 cin
.
In fact, you can replace cin
with any C++ standard input stream.
std::stringstream ss("The quick brown fox jumped over the lazy dogs.");
copy(istream_iterator<string>(ss), istream_iterator<string>(),
back_inserter(col));
有主意吗? col
将包含您传递给 std :: stringstream
的字符串的单词.
Got the idea? col
will contain words of the string which you passed to std::stringstream
.
这篇关于如何使用std :: copy从文件流直接读取到容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!