直接使用copy函数将vector写入文件时,每行数据之间没有分割,如果想要将vector的每一项写成文件中的每一行,采用下面方法。
注意,不同平台的换行符不同,windows下是\n\r
参考网站:http://stackoverflow.com/questions/6406356/writing-vector-values-to-a-file
Using std::ofstream
, std::ostream_iterator
and std::copy()
is the usual way to do this. Here is an example with std::string
s:
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> example;
example.push_back("this");
example.push_back("is");
example.push_back("a");
example.push_back("test");
std::ofstream output_file("./example.txt");
std::ostream_iterator<std::string> output_iterator(output_file, "\n");
std::copy(example.begin(), example.end(), output_iterator);
}
转载请注明:jinglingshu的博客 » Writing Vector Values to a File 将vector写入文件