C++ 读取文件并为地图赋值
我必须读入一个用逗号解析的文件 文件示例:C++ 读取文件并为地图赋值,c++,file,parsing,C++,File,Parsing,我必须读入一个用逗号解析的文件 文件示例: class Instructor { private: int Id; string name; string dept; string emailAddress; public: static Instructor findInstructor(int ID); static map<int,In
class Instructor {
private:
int Id;
string name;
string dept;
string emailAddress;
public:
static Instructor findInstructor(int ID);
static map<int,Instructor> instructorList;
Instructor():Id(-1),name(""),dept(""),emailAddress(""){};
Instructor(int ID, string name, string dept,string email):Id(ID),name(name),dept(dept),emailAddress(email){};
static int loadInstructors();
string getName() {return name;}
int getId() {return Id;}
string getDept() {return dept;}
string getEmailAddress() {return emailAddress;}
friend ostream& operator<< (ostream& out,Instructor i)//overloading << operator
{
out<<i.name<<"("<<i.Id<<")";
return out;
}
};
当我浏览地图并打印每个讲师时,这是我的输出:
代码:
文件:
赋值运算符
=
是否重载?@AndrewDunn否唯一重载的是讲师构造函数中的,命名类变量和函数参数是一种非常不安全的做法。我建议你改变你的论点,使之与你的课堂不同vars@Gmercer015只要只在初始值设定项列表中使用,编译器就不会有任何歧义。@user3341518忘记我的答案吧,这太傻了!对于这种情况,您的代码是不可编译的。我建议您将您的代码作为一个最小的示例发布,这样可以重现问题(请不要使用行号),并且可以通过在线IDE等其他工具在此处轻松检查。
int Instructor::loadInstructors()
{
string comma;
string line;
ifstream myfile("instructor.dat");
string name,email = "";
string dept = "";
int id;
if (myfile.is_open())
{
while (getline(myfile,line))
{
//parse line
string myText(line);
istringstream iss(myText);
if(!(iss>>id)) id=0;
//parses the string into independent string variables
iss.ignore(1,',');
std::getline(iss,name,',');
std::getline(iss,dept,',');
std::getline(iss,email,',');
Instructor newInstructor(id,name,dept,email);
Instructor::instructorList.insert(std::pair<int,Instructor>(id,newInstructor));
}
myfile.close();
}
else
{
cout << "Unable to open file:" << endl;
return -1;
}
return 0;
cout<<i.name<<"("<<i.id<<")"<<endl;
Instructor():Id(-1),name(""),dept(""),emailAddress(""){};
Instructor(int ID, string name, string dept,string email):Id(ID),name(name),dept(dept),emailAddress(email){};
for (map<int,Instructor>::iterator it = Instructor::instructorList.begin();it!=Instructor::instructorList.end();++it)
{
Instructor instruct = it->second;
std::cout<<(it->second)<<endl;
}
(-1)
(-1)
(-1)
Instructor List
(-1)
(-1)
Dr rmith(2)
(-1)
Dr all(4)
Dr tll(5)
Dr yll(6)
Dr ull(7)
Dr ill(8)
1 0,Dr all,Math,wall@eng.ua.edu
2 4,Dr all,Math,wall@eng.ua.edu
3 1,Dr Wall,Math,wall@eng.ua.edu
4 2,Dr rmith,CS,smith@eng.ua.edu
5 3,Dr all,Math,wall@eng.ua.edu
6 4,Dr rll,Math,wall@eng.ua.edu
7 5,Dr tll,Math,wall@eng.ua.edu
8 6,Dr yll,Math,wall@eng.ua.edu
9 7,Dr ull,Math,wall@eng.ua.edu
10 8,Dr ill,Math,wall@eng.ua.edu