读取文件并将值分配给地图

时间:2014-02-24 19:43:28

标签: c++ file parsing

我必须阅读用逗号解析的文件。

文件示例:

  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;
          }

  };

这是我用来扩展/解析文件的代码。

 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;

在班级I上&lt;&lt;操作员以特定格式打印

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

0 个答案:

没有答案