将向量的内容写入文件 C++
writing content of vector to file c++
我试图将我的矢量内容写入文件。为此,我编写了一段代码,如下所示:
int main()
{
ofstream outputfile("test.txt");
vector<int>temp;
temp.push_back(1);
temp.push_back(2);
temp.push_back(3);
for(int i=0;i<temp.size();i++)
outputfile<<temp[i]<<"n";
}
当我写这篇文章时,我可以轻松地做我想做的事。 文件的内容是:
123
但是,当我想从反向将我的矢量写入文件时(如下所示)。我一无所获。只是空文件。有人可以帮助我吗?提前谢谢。
for(int i=temp.size()-1;i>=0;i--)
outputfile<<temp[i]<<"n";
您可以使用
std::copy(temp.rbegin(), temp.rend(),
std::ostream_iterator<int>(outputfile, "n"));
而这段代码:
for(int i=temp.size()-1;i>=0;i--)
outputfile<<temp[i]<<"n";
使用 VS12 在我的窗户上工作正常。
您可以在 1 行中完成所有操作:
std::copy(temp.rbegin(), temp.rend(), std::ostream_iterator<int>(outputFile, "n"));
使用反向迭代器:
for (std::vector<int>::reverse_iterator it = myvector.rbegin(); it != myvector.rend(); ++it)
或者在代码中,从 size() - 1
开始 for 循环:
for(int i=temp.size()-1;i>=0;i--)
而不是
for(int i=temp.size();i>=0;i--)
std::copy(head_buff.rbegin(), head_buff.rend(),
std::ostream_iterator<std::string>(data_pack, "n"));
但使用#include<fstram>#include<iterator> #include<osstream>
第二种方法是遍历整个向量并将内容复制到字符串中然后将字符串写入 Ofstream即
std::string somthing;
for(std::vector<std::string>::const_iterator i = temp.begin();i!=temp.end(); ++i)
{
something+=*i;
}
然后将字符串(某些东西)写入 Ofstream IE
std::ofstram output;
output.open("test.txt",std::ios_base::trunc)
if(output.fail())
std::cerr<<"unable to open the file"std::endl;
output << something;
//after writing close file
output.close();
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到