I have the following code and I want to build an object. How could I do it? Any ideas? The class is of type {sting,int,int}.
code:
void StudentRepository::loadStudents(){
ifstream fl;
fl.open("studs.txt");
Student A();
if(fl.is_open()){
while(!(fl.eof())){
getline(???); //i dont knwo houw coudl i limit what i want were...
}
}
else{
cout<<"~~~ File couldn't be open! ~~~"<<endl;
}
}
Save to file funcntion:
void StudentRepository::saveStudents(){
ofstream fl;
fl.open("studs.txt");
if(fl.is_open()){
for(unsigned i=0; i<students.size(); i++){
fl<<students[i].getName();
fl<<",";
fl<<students[i].getID();
fl<<",";
fl<<students[i].getGroup();
fl<<","<<endl;
}
}
else{
cout<<"~~~ File couldn't be open! ~~~"<<endl;
}
I tried to implement some limits but that is not working... How canI do this?
Initially I just wrote the object to file but it is harder to get them back to the object.... File content:
maier ewew 123 232
tudor efsw 13 2323
Would overloading the input and output operators for the Student type work for you?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Student {
public:
Student() : name(""),id(0),group(0) {}
Student(const string &_name, const int &_id, const int &_group) : name(_name), id(_id), group(_group) {}
friend ostream &operator<<(ostream &out, const Student &stud);
friend istream &operator>>(istream &in, Student &stud);
private:
string name;
int id;
int group;
};
ostream &operator<<(ostream &out, const Student &stud) {
out << stud.name << " " << stud.id << " " << stud.group << endl;
return out;
}
istream &operator>>(istream &in, Student &stud) {
string name, surname;
in >> name >> surname >> stud.id >> stud.group;
stud.name = name + " " + surname;
return in;
}
int main(int argc, char **argv) {
Student john("john doe", 214, 43);
Student sally("sally parker", 215, 42);
Student jack("jack ripper", 114, 41);
ofstream out("studentfile.txt");
out << john;
out << sally;
out << jack;
out.close();
Student newstud;
ifstream in("studentfile.txt");
in >> newstud;
cout << "Read " << newstud;
in >> newstud;
cout << "Read " << newstud;
in >> newstud;
cout << "Read " << newstud;
in.close();
return 0;
}
Adding some standard checks for I/O to check that whatever you are reading is valid should do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.