#include <iostream>
#include <fstream>
using namespace std;
class info {
private:
char name[15];
char surname[15];
int age;
public:
void input(){
cout<<"Your name:"<<endl;
cin.getline(name,15);
cout<<"Your surname:"<<endl;
cin.getline(surname,15);
cout<<"Your age:"<<endl;
cin>>age;
to_file(name,surname,age);
}
void to_file(char name[15], char surname[15], int age){
fstream File ("example.bin", ios::out | ios::binary | ios::app);
// I doesn't know how to fill all variables(name,surname,age) in 1 variable (memblock)
//example File.write ( memory_block, size );
File.close();
}
};
int main(){
info ob;
ob.input();
return 0;
}
I don’t know how to write more than 1 variable into a file, please help, I included an example 😉 Maybe there are better ways to write to a file, please help me with this, it’s to hard for me to solve.
For a text file, you could easily output one variable per line using a similar
<<to the one you use withstd::cout.For a binary file, you need to use
std::ostream::write(), which writes a sequence of bytes. For yourageattribute, you’ll need toreinterpret_castthis toconst char*and write as many bytes as is necessary to hold anintfor your machine architecture. Note that if you intend to read this binary date on a different machine, you’ll have to take word size and endianness into consideration. I also recommend that you zero thenameandsurnamebuffers before you use them lest you end up with artefacts of uninitialised memory in your binary file.Also, there’s no need to pass attributes of the class into the
to_file()method.A sample data file may look like this: