8.4 代码:以一行文本为元素
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> fvec;
string line;
if ( argc < 2 ) {
cout << "usage: ./file filename" << endl;
return 0;
}
//输入文件名作为argv[1]
ifstream input(argv[1]);
while ( getline(input, line) ) {
fvec.push_back(line);
}
for ( auto l : fvec )
cout << l << endl;
return 0;
}
8.5 代码:以单词为元素
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> fvec;
string word;
if ( argc < 2 ) {
cout << "usage: ./file2 filename" << endl;
return 0;
}
ifstream input(argv[1]);
while ( input >> word ) {
fvec.push_back(word);
}
for ( auto l : fvec )
cout << l << endl;
return 0;
}
8.6--8.7 代码:从一个文件读取输入记录,将结果保存到另一个文件
#include <iostream>
#include <fstream>
#include "Sales_data.h"
using namespace std;
int main(int argc, char *argv[])
{
ifstream input(argv[1]);
ofstream output(argv[2]);
Sales_data total;
if (read(input, total)) {
Sales_data trans;
while(read(input, trans)) {
if (total.isbn() == trans.isbn())
total.combine(trans);
else {
print(output, total) << endl;
total = trans;
}
print(output, total) << endl;
}
} else {
cerr << "No data?!" << endl;
}
return 0;
}
8.8 代码:输出追加模式(app)
#include <iostream>
#include <fstream>
#include "Sales_data.h"
using namespace std;
int main(int argc, char *argv[])
{
ifstream input(argv[1]);
ofstream output;
//模式为输出追加
output.open(argv[2], ofstream::app);
Sales_data total;
if (read(input, total)) {
Sales_data trans;
while(read(input, trans)) {
if (total.isbn() == trans.isbn())
total.combine(trans);
else {
print(output, total) << endl;
total = trans;
}
print(output, total) << endl;
}
} else {
cerr << "No data?!" << endl;
}
output.close();
return 0;
}
这篇博客主要涵盖了C++ Primer第五版中8.2.1至8.2.2章节的练习内容,包括以一行文本为元素的代码实现、以单词为元素的处理、从文件读取输入记录并保存到另一个文件的技巧,以及使用输出追加模式(app)进行文件操作的示例。
1846

被折叠的 条评论
为什么被折叠?



