[英]Build Class object from txt file line
我有以下代碼,我想構建一個對象。 我怎么能這樣做? 有任何想法嗎? 該類的類型為{sting,int,int}。
碼:
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;
}
}
保存到文件功能:
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;
}
我試圖實施一些限制,但這不起作用......我怎么能這樣做?
最初我只是將對象寫入文件但是很難讓它們回到對象中....文件內容:
maier ewew 123 232
tudor efsw 13 2323
重載學生類型的輸入和輸出操作符會為你工作嗎?
#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;
}
添加一些I / O標准檢查以檢查您正在閱讀的內容是否有效應該這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.