iostream迭代器操作"txt文本文件"无法写入的思考
来源:互联网 发布:pss监控软件下载 编辑:程序博客网 时间:2024/05/21 17:31
题:从“in.txt”读取数据,然后分奇偶分别存到“out_odd.txt”和“out_even.txt”中
#include <QCoreApplication>#include <iostream>#include <fstream>#include <iterator>#include <vector>#include <string>#include <stdlib.h>using std::cout; using std::endl;using std::vector;using std::string;int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); std::ifstream ifs("./in.txt"); std::ofstream ofs_odd("./out_odd.txt",std::ios::out), ofs_even("./out_even.txt",std::ios::out); std::istream_iterator<int> in(ifs), in_eof; std::ostream_iterator<int> out_odd(ofs_odd, " "), out_even(ofs_even, "\n"); std::for_each(in, in_eof, [&out_odd, &out_even](const int i) { *(i & 0x1 ? out_odd : out_even)++ = i; //cout << i; }); return a.exec();}出现了一个很奇怪的现象,文件out_odd.txt”和“out_even.txt”虽然创建了,可是文件是空,测试了一下“in.txt”中的数已经读出来了,为什么会出现这样奇怪的文件呢?我一度怀疑是不是编码方式不对,后来偶然情况下,加入把打开文件关闭的语句,文件神奇的有数据了。
int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); std::ifstream ifs("./in.txt"); std::ofstream ofs_odd("./out_odd.txt",std::ios::out), ofs_even("./out_even.txt",std::ios::out); std::istream_iterator<int> in(ifs), in_eof; std::ostream_iterator<int> out_odd(ofs_odd, " "), out_even(ofs_even, "\n"); std::for_each(in, in_eof, [&out_odd, &out_even](const int i) { *(i & 0x1 ? out_odd : out_even)++ = i; cout << i; }); ofs_odd.close(); ofs_even.close(); return a.exec();}
为什么会出现这种情况呢?原来文件输出的数据先是放到一个“basic_streambuf()”的地方,并非立马刷新的,当调用file.close()的时候,数据流被刷新到文件中,我们可以直接加入刷新操作,也可以将数据刷新到文件中。
int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); std::ifstream ifs("./in.txt"); std::ofstream ofs_odd("./out_odd.txt",std::ios::out), ofs_even("./out_even.txt",std::ios::out); std::istream_iterator<int> in(ifs), in_eof; std::ostream_iterator<int> out_odd(ofs_odd, " "), out_even(ofs_even, "\n"); std::for_each(in, in_eof, [&out_odd, &out_even](const int i) { *(i & 0x1 ? out_odd : out_even)++ = i; cout << i; }); ofs_odd << std::endl; ofs_even << std::endl; return a.exec();}
0 0
- iostream迭代器操作"txt文本文件"无法写入的思考
- Code17写入.txt/文本文件
- C#写入TXT文本文件
- C#写入TXT文本文件
- asp 操作 txt 文本文件
- 【QTP】写入txt文件的操作
- C++文件读写操作(一)将字母表写入TXT文本文件
- java逐行读取和写入文本文件txt
- C++往txt文本文件里面写入内容
- .Net C# Txt文本文件操作
- ObjectArx开发对txt文本文件的操作一例
- QTP中实现对文本文件(txt)的读写操作
- QTP实现对文本文件(txt)的读操作
- 将TXT批量转换成PDF文本文件的操作
- jsp对文本文件的读取写入等操作
- 在MFC中,如何将Unicode的CString中文字符写入文本文件TXT中
- 记事本.txt文件的读取和写入操作
- C++文件操作无法写入的问题
- Linux进阶命令
- React Native 中组件的生命周期
- 使用git(一)git简介及基本工作流程
- leetcode之位运算取得数组中只出现一次的一个数
- Linux中强大且常用命令:find、grep
- iostream迭代器操作"txt文本文件"无法写入的思考
- poj 2096
- Java虚拟机详解----常用JVM配置参数
- CentOS7配置防火墙
- Educational Codeforces Round 16 B. Optimal Point on a Line【水】
- java List多字段排序
- 一个监督的赫布学习(Hebb Learning)的例子
- Maximal Square
- 56. Merge Intervals 对区间进行合并