题:从“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();
}