17.1
方法一:采用peek方法(注意该方法只读取下一个字符但不抽取)
//main.cpp
#include <iostream>
int main()
{
using namespace std;
cout << "enter your string to count<$ for end> :\n";
int count = 0;
int i = 0;
char ch;
char str[20];//存放$之前的字符
char next[20];//存放$及其后面的字符
while ((ch=cin.peek())!='$')//只能查看下一个字符
{
count++;
cin.get(str[i++]);//抽取字符否则peek将永远为第一个字符
}
str[i] = '\0';//使str成为一个字符串便于输出
cout <<"string befor $ "<< str
<<" include "<<count<<" characters.\n";
cin.getline(next, 20);
cout << "string after $: " << next;
return 0;
}
方法二:采用整行输入的get方法(不抽取分界符)
//main.cpp
#include <iostream>
#include<string>
int main()
{
using namespace std;
cout << "enter your string to count<$ for end> :\n";
char str[20];
string next;
cin.get(str, 20, '$');
getline(cin, next);
cout << "string befor $: " << str << endl;
cout << "next string: " << next << endl;
return 0;
}
17.2
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
int main(int argc, char *argv[])
{
using namespace std;
if (argc == 1)
{
cerr << "no file assign .\n";
exit(EXIT_FAILURE);
}
ofstream fout;
for (int i = 1; i < argc; i++)
{
fout.open(argv[i]);
if (!fout.is_open())
{
cout << "Could not open " << argv[i] << endl;
fout.clear();
continue;
}
cout << "enter your characters to file<EOF to quit> " << argv[i] << endl;
char ch;
while ((ch=cin.get())!=EOF)
{
fout << ch;
}
fout.clear();
fout.close();
ifstream fin(argv[i]);
string str;
getline(fin, str);
cout << "your string in file " << argv[i] << ": "
<< str<<endl;
fin.close();
}
return 0;
}
Windows执行步骤:1)在编译环境下执行生成exe可执行文件 ,在提示框中查看文件路径
2)打开cmd(windows10系统下搜索即可)
3)在cmd中输入文件路径以及所需的文件即可
注意事项:1)可执行文件路径一定要输入正确,不用管cmd命令框中默认的文件路径,直接重新输入即可(找到文件复制路径)
2)输入的命令为:路径/可执行文件名.exe 文件名;可执行文件一定要加后缀
3)如果需要处理的文件不存在,将自动创建一个新的文件,若需要文件为txt格式,必须在输入的文件名后加.txt后缀
17.3
//在命令窗口运行前至少需要创建argv[2]文件,并存入数据
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
int main(int argc, char *argv[])
{
using namespace std;
if (argc == 1)
{
cerr << "no file assign .\n";
exit(EXIT_FAILURE);
}
ofstream fout(argv[1]);//argv[1]为输入的第一个文件名其内容将被argv[2]覆盖
if (!fout.is_open())
{
cerr << argv[1] << " Could not open.\n";
fout.clear();
exit(EXIT_FAILURE);
}
ifstream fin(argv[2]);
if (!fin.is_open())
{
cerr << argv[2] << " Could not open.\n";
fin.clear();
exit(EXIT_FAILURE);
}
char ch;
while ((ch=fin.get())!=EOF)//读取argv[2]中数据
{
fout << ch;//将argv[2]中数据输出到argv[1]
}
fout.close();
fin.close();
cout << "done\n";
return 0;
}
17.4
//在运行前至少要创建两个输入文件,并写入数据,
//且文件要创建在在项目文件目录中,
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
int main()
{
using namespace std;
ifstream in1("input1.txt");
if (!in1.is_open())
{
cerr << "input1.txt could not open.\n";
exit(EXIT_FAILURE);
}
ifstream in2("input2.txt");
if (!in2.is_open())
{
cerr << "input2.txt could not open.\n";
exit(EXIT_FAILURE);
}
ofstream out("output.txt");
if (!out.is_open())
{
cerr << "output.txt could not open.\n";
exit(EXIT_FAILURE);
}
string temp;
char ch;
while ((ch=in1.peek())!=EOF)
{
getline(in1, temp);
out << temp<<' ';
if ((ch = in2.peek()) != EOF)
{
getline(in2, temp);
out << temp << endl;
}
}
cout << "done\n";
return 0;
}
17.5
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<set>
int main()
{
using namespace std;
ifstream ma("mat.dat");
if (!ma.is_open())
{
cerr << "mat.dat could not open.\n";
exit(EXIT_FAILURE);
}
ifstream pa("pat.dat");
if (!pa.is_open())
{
cerr << "pat.dat could not open.\n";
exit(EXIT_FAILURE);
}
string temp;
set<string>mat;//用于存储mat.dat文件内容并排序
set<string>pat;//用于存储pat.dat文件内容并排序
set<string>patmat;//用于存储mat.dat和pat.dat文件内容并删除重复内容以及排序
while (!ma.eof())//将mat.dat文件内容复制到ma和patmat容器
{
ma >> temp;
mat.insert(temp);
patmat.insert(temp);
}
cout << "Mat's friends in order:\n";
for (set<string>::iterator iter = mat.begin(); iter != mat.end(); iter++)
cout << *iter<<endl;
cout << endl;
while (!pa.eof())
{
pa >> temp;
pat.insert(temp);
patmat.insert(temp);
}
cout << "Pat's friends in order:\n";
for (auto iter = pat.begin(); iter != pat.end(); iter++)
cout << *iter<<endl;
ofstream out("matnpat.dat");
for (auto iter = patmat.begin(); iter != patmat.end(); iter++)
out << *iter << endl;
return 0;
}
17.6
// emp.h给每个类重载>>\<<可以直接将数据输出、输入到文档(行不通),不能访问基类私有成员,用函数实现,文件输出输入
#pragma once
#include <iostream>
#include <string>
class employee
{
public:
employee();
employee(const std::string & fn, const std::string & ln,
const std::string & j);
virtual void ShowAll() const;
virtual void SetAll();
virtual void writeall(std::ostream&os);//输出到文件
virtual void getall(std::istream&is);//从文件输入
friend std::ostream &
operator<<(std::ostream & os, const employee & e);
virtual ~employee() ;
private:
std::string fname;
std::string lname;
std::string job;
};
class manager : virtual public employee
{
private:
int inchargeof;
protected:
int InChargeOf() const { return inchargeof; }
int & InChargeOf() { return inchargeof; }
public:
manager();
manager(const std::string & fn, const std::string & ln,
const std::string & j, int ico = 0);
manager(const employee & e, int ico);
manager(const manager & m);
virtual void ShowAll() const;
virtual void SetAll();
virtual void writeall(std::ostream&os);
virtual void getall(std::istream&is);
};
class fink : virtual public employee
{
private:
std::string reportsto;
protected:
const std::string ReportsTo() const { return reportsto; }
std::string & ReportsTo() { return reportsto; }
public:
fink();
fink(const std::string & fn, const std::string & ln,
const std::string & j, const std::string & rpo);
fink(const employee & e, const std::string & rep);
fink(const fink & e);
virtual void ShowAll() const;
virtual void SetAll();
virtual void writeall(std::ostream&os);
virtual void getall(std::istream&is);
};
class highfink : public manager, public fink
{
public:
highfink();
highfink(const std::string & fn, const std::string & ln,
const std::string & j, const std::string & rpo,
int ico);
highfink(const employee & e, const std::string & rpo, int ico);
highfink(const fink & f, int ico);
highfink(const manager & m, const std::string & rpo);
highfink(const highfink & h);
virtual void ShowAll() const;
virtual void SetAll();
virtual void writeall(std::ostream&os);
virtual void getall(std::istream&is);
};
//emp.cpp
#include<iostream>
#include<iomanip>
#include"emp.h"
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::setw;
//employee method
employee::employee()
{
fname = lname = job = "none";
}
employee::employee(const std::string & fn, const std::string & ln,
const std::string & j)
{
fname = fn;
lname = ln;
job = j;
}
void employee::ShowAll() const
{
cout << "first name: " << fname
<< "\nlast name: " << lname
<< "\njob: " << job << endl;
}
void employee::SetAll()
{
cout << "enter first name: ";
getline(cin, fname);
cout << "enter last name: ";
getline(cin, lname);
cout << "enter job: ";
getline(cin, job);
}
void employee::writeall(std::ostream&os)
{
os << fname << " " << lname ;
}
void employee::getall(std::istream&is)//按输出到文件的顺序从文件读取数据
{
//按输出到文件的顺序从文件读取数据
(is >> fname).get();//类型别名后第一个数据是fname,get方法用于吸收各数据之间的空格
(is >> lname).get();
(is >> job).get();
//将读取的数据输出屏幕
cout<<setw(15) << fname << " "
<<setw(15)<< lname << " "
<<setw(15)<< job;
}
std::ostream &operator<<(std::ostream & os, const employee & e)
{
os << e.fname << "." << e.lname << endl;
return os;
}
employee::~employee() {};
//manager method
manager::manager()
:employee()
{
inchargeof = 0;
}
manager::manager(const std::string & fn, const std::string & ln,
const std::string & j, int ico)
: employee(fn, ln, j)
{
inchargeof = ico;
}
manager::manager(const employee & e, int ico)
: employee(e)
{
inchargeof = ico;
}
manager::manager(const manager & m)
: employee(m)
{
inchargeof = m.inchargeof;
}
void manager::ShowAll() const
{
employee::ShowAll();
cout << "inchargeof: " << inchargeof ;
}
void manager::SetAll()
{
employee::SetAll();
cout << "enter inchargeof: ";
cin >> inchargeof;
}
void manager::writeall(std::ostream&os)
{
employee::writeall(os);
os << " " << inchargeof;
}
void manager::getall(std::istream&is)
{
employee::getall(is);
(is >> inchargeof).get();
cout << " " <<setw(15)<< inchargeof;
}
//fink method
fink::fink()
:employee()
{
reportsto = "none";
};
fink::fink(const std::string & fn, const std::string & ln,
const std::string & j, const std::string & rpo)
:employee(fn, ln, j)
{
reportsto = rpo;
}
fink::fink(const employee & e, const std::string & rep)
: employee(e)
{
reportsto = rep;
}
fink::fink(const fink & e)
: employee(e)
{
reportsto = e.reportsto;
}
void fink::ShowAll() const
{
employee::ShowAll();
cout << "reportsto: " << reportsto << endl;
}
void fink::SetAll()
{
employee::SetAll();
cout << "enter reportsto: ";
cin >> reportsto;
}
void fink::writeall(std::ostream&os)
{
employee::writeall(os);
os <<" "<< reportsto;
}
void fink::getall(std::istream&is)
{
employee::getall(is);
(is >> reportsto).get();
cout << " " <<setw(15)<< reportsto;
}
//highfink method
highfink::highfink()
: manager(), fink() {};
highfink::highfink(const std::string & fn, const std::string & ln,
const std::string & j, const std::string & rpo,
int ico)
: manager(fn, ln, j, ico), fink(fn, ln, j, rpo) {};
highfink::highfink(const employee & e, const std::string & rpo, int ico)
: manager(e, ico), fink(e, rpo) {};
highfink::highfink(const fink & f, int ico)
: manager(f, ico), fink(f) {};
highfink::highfink(const manager & m, const std::string & rpo)
: manager(m), fink(m, rpo) {};
highfink::highfink(const highfink & h)
: manager(h), fink(h) {};
void highfink::ShowAll() const
{
employee::ShowAll();
cout << "InChangeOf: " << InChargeOf() << endl
<< "reportsto: " << ReportsTo() << endl;
}
void highfink::SetAll()
{
manager::SetAll();
cin.get();//吸收输入int型inchargeof后的换行符
cout << "enter ReportsTo: ";
getline(cin, fink::ReportsTo());
}
void highfink::writeall(std::ostream&os)
{
manager::writeall(os);
os <<" "<< fink::ReportsTo();
}
void highfink::getall(std::istream&is)
{
manager::getall(is);
(is >> fink::ReportsTo()).get();
cout << " " <<setw(15)<< fink::ReportsTo();
}
//main.cpp
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
#include"emp.h"
const int MAX = 10;
int main()
{
using namespace std;
employee *pc[MAX];
fstream emp("17.6.txt",ios_base::in|ios_base::out|ios_base::app);
if (!emp.is_open())
{
cout << "Could not open file.\n";
exit(EXIT_FAILURE);
}
for (int i = 0; i < MAX; i++)//输入数据
{
cout << "enter data:\n"
<< "choice type to add \n"
<< left
<< setw(20) << "1 for employee "
<< setw(20) << "2 for manager " << endl
<< setw(20) << "3 for fink "
<< setw(20) << "4 for highfink " << endl
<< setw(20) << "q to quite" << endl;
char choice;
cin >> choice;
cin.get();//吸收换行符
if (choice == 'q')
break;
else if (choice<'1' || choice>'4')
{
cout << "Please enter 1、2、3、4 or q\n";
continue;
}
else
{
switch (choice)
{
case '1':
{
pc[i] = new employee;
pc[i]->SetAll();
break;
}
case '2':
{
pc[i] = new manager;
pc[i]->SetAll();
break;
}
case '3':
{
pc[i] = new fink;
pc[i]->SetAll();
break;
}
case '4':
{
pc[i] = new highfink;
pc[i]->SetAll();
break;
}
}
}
emp << choice << " ";
pc[i]->writeall(emp);
emp << endl;//用于文件中换行
}
cout << "now the file includes:\n";
char type;
employee *p=nullptr;
while (!emp.eof())//从文件输入数据
{
(emp >> type).get();//get用于吸收文件中类型标记后的空格
switch (type)
{
case '1':
p= new employee;
break;
case '2':
p = new manager;
break;
case'3':
p = new fink;
break;
case'4':
p = new highfink;
break;
}
p->getall(emp);
cout << endl;
}
cout << "done\n";
return 0;
}
17.7
//main.cpp
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>//STL算法库文件,for_each()函数
#include<fstream>
using namespace std;
void ShowStr(const string &str);
void GetStrs(ifstream&fin, vector<string>&vi);
class Store
{
private:
ofstream &file;//必须为引用
size_t len;
public:
Store(ofstream&fout) :file(fout) {};//将file初始化为指定的文件
void operator()(const string &);
};
void Store::operator()(const string &str)
{
len = str.length();
//file <<len;插入运算法将内容存储为文本
file.write((char*)&len, sizeof(size_t));//write方法的数值用法
file.write(str.data(), len);
}
int main()
{
vector<string>vostr;
string temp;
cout << "Enter string(empty line to quit):\n";
while (getline(cin,temp)&&temp[0]!='\0')
{
vostr.push_back(temp);
}
cout << "Here is your input.\n";
for_each(vostr.begin(), vostr.end(), ShowStr);
ofstream fout("string.dat", ios_base::out | ios_base::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));
//for_each函数的第三个参数只能用一元函数,并对前两个参数指定的范围
//内的每个对象使用该函数,这里的第三个参数是创建一个Store对象并对其初始化
//而不是将fout作为函数符的参数,实际上指出的迭代器才是Store函数符的参数
fout.close();
vector<string>vistr;
ifstream fin("string.dat", ios_base::in | ios_base::binary);
if (!fin.is_open())
{
cerr << "Could not open file for input.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the string read from the file:\n";
for_each(vistr.begin(), vistr.end(), ShowStr);
return 0;
}
void ShowStr(const string &str)
{
cout << str << endl;
}
void GetStrs(ifstream&fin, vector<string>&vi)
{
while (!fin.eof())
{
size_t len = 0;
fin.read((char*)&len, sizeof(size_t));
char ch;
string temp;
for (size_t i = 0; i < len; i++)
{
//不能用fin>>temp[i]代替下面两行,抽取运算符>>
//用于文本格式数据,这里是二进制格式
fin.read((char*)&ch, sizeof(size_t));//将每个字符读取到ch中
temp.push_back(ch);//将文件中读取的每个字符依次存入temp中
}
vi.push_back(temp);//将一个完整的string存入到vector容器中
}
}