#include <fstream>
using std::istringstream; using std::ifstream; using std::ofstream; using std::ostringstream;
头文件fstream,四个类型。
istringstream:字符串流类型
ifstream:读入文件内的字符串流
ofstream:打开一个文件,默认是截取,即文件的旧数据被丢弃。
? ? ? ? ? ? ? ? 因此可以用ofstream::app,app(append)追加、添加。
ostringstream:输出流,可以用<<不断向其添加字符串。
#include "mylib7.h"
#include <fstream>
using std::istringstream;
using std::ifstream;
using std::ofstream;
using std::ostringstream;
int main() {
string file1 = "s.txt";//filename
string file2 = "s2.txt";
ifstream input(file1);//input is the file1's contents
ofstream out;//out is a file will be writen
ostringstream ofile;//ofile is a stream to store strings
string line;
string word;
vector<string> vst;
string::size_type cnt=0;
while (getline(input, line)) {//take a line from stream input to line
vst.push_back(line);
++cnt;
istringstream record(line);//make the record to store line's content
while (record >> word) {
cout << word<<' ';
ofile << word << ' ';//add string to ostream ofile
}
cout << endl;
ofile << endl;
}
for (int i = 0; i < cnt; ++i) {
istringstream record(vst[i]);
while (record >> word) {
cout << word << ' ';
}
cout << endl;
}
out.open(file2, ofstream::app);//open file2 by append
out << ofile.str();
out.close();
}
|