我们可以利用fstream类(头文件fstream),因为他有一个可以传文件路径的构造函数,所以我们可以在实例化的时候传递文件路径
#include <fstream>
fstream file("C:\\Users\\86132\\Desktop\\大二上\\C++\\实验\\实验二\\4、职工类Employee\\Employee.txt");
然后就可以把file当作 cin 和 cout 来用
比如,从文件读取信息:
file >> name >> street >> city >> province >> zip;
向文件写入信息:
file << name << endl
<< street << endl
<< city << endl
<< province << endl
<< zip << endl;
但是从文本文档(后缀为.txt)读取中文时可能会出现乱码,原因是文本文档编码方式默认是UTF-8,我们需要修改它的编码方式为ANSC
如下图,新建以后默认编码方式为UTF-8