如何使用文件 I/O c++
How to use file I/O c++
首先我正在尝试创建一个文件并写入它,它不允许我使用"<<"写入文件,第二部分我试图从文件中读取数据,但我不确定这是正确的方法,因为我想将数据保存到对象中,以便以后可以在程序中使用这些对象。任何帮助或建议将不胜感激。提前致谢
void Employee::writeData(ofstream&)
{
Employee joe(37," ""Joe Brown"," ""123 Main ST"," ""123-6788", 45, 10.00);
Employee sam(21,"nSam Jones", "n 45 East State", "n661-9000",30,12.00);
Employee mary(15, "nMary Smith","n12 High Street","n401-8900",40, 15.00);
ofstream outputStream;
outputStream.open("theDatafile.txt");
outputStream << joe << endl << sam << endl << mary << endl;
//it says that no operator "<<"matches this operands, operands types are std::ofstream<<employee
outputStream.close();
cout<<"The file has been created"<<endl;
}
void Employee::readData(ifstream&)
{
//here im trying to open the file created and read the data from it, but I'm strugguling to figure out how to read the data and save it into de class objects.
string joe;
string sam;
string mary;
ifstream inputStream;
inputStream.open("theDatafile.txt");
getline(inputStream, joe);
getline(inputStream, sam);
getline(inputStream, mary);
inputStream.close();
}
您收到的错误是因为您需要为雇员类定义输出运算符。
ostream& operator<<(ostream& _os, const Employee& _e) {
//do all the output as necessary: _os << _e.variable;
}
最好同时实现输入运算符:
istream& operator>>(istream& _is, Employee& _e) {
//get all the data: _is >> _e.variable;
}
您应该使这些友元函数对您的班级员工:
class Employee {
public:
//....
friend ostream& operator<<(ostream& _os, const Employee& _e);
friend istream& operator>>(istream& _is, Employee& _e);
//....
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何确定我已使用非编码文件到达 EOF?
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 使用CMake创建QML插件
- 使用 LLVM 的 libc++ 时,__1 符号从何而来?
- 在std::cout之后使用std::cin时,换行符从何而来
- 为什么以及在何处在C++中使用引用和指针
- 基例如何影响使用递归函数的哪些行