axyd

C++ File to Vector of Objects

Oct 16th, 2016
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #####################
  2. ####  headers.h  ####
  3. #####################
  4. #ifndef SOMETHING_H
  5. #define SOMETHING_H
  6. #include <iostream>
  7.  
  8. struct studentinfo {
  9.     int id;
  10.     string surname;
  11.     string name;
  12.     string year;
  13.     int taken;
  14.     int grad;
  15.     string major;
  16.     string minor;
  17.  
  18.     studentinfo(int, string, string, string, int, int, string, string);
  19. };
  20. #endif
  21.  
  22. #####################
  23. #### methods.cpp ####
  24. #####################
  25.  
  26. #include <iostream>
  27. #include <vector>
  28. #include <fstream>
  29. #include <string>
  30. #include <sstream>
  31. #include "headers.h"
  32. using namespace std;
  33.  
  34. studentinfo::studentinfo(int i, string sn, string nm, string yr, int tkn, int g, string ma, string mi)
  35.     :id(i),surname(move(sn)),name(move(nm)),year(move(yr)),taken(move(tkn)), grad(move(g)),major(move(ma))
  36.     ,minor(move(mi)) {};
  37.  
  38.  
  39. vector<studentinfo> CollegeStudent::vstuds() {
  40. //remove header row junk -  Adam @ http://stackoverflow.com/a/164367/6793751
  41.     vector<studentinfo> vTmp;
  42.     fstream f(rosterfile);
  43.     string junk;
  44.     getline(f,junk,'\n'); //skip header row
  45.  
  46.     string line=" ";
  47.     int rktr=0; //rows
  48.     while(getline(f,line,'\n')) {
  49.         studentinfo *si= new studentinfo(0,"","","",0,0,"","");
  50.         stringstream ss(line);
  51.         string in_line;
  52.         int cktr=0; //cols
  53.         vector<string> vstest;
  54.         while(getline (ss, in_line, ',')) {
  55.             vstest.push_back(in_line);
  56.             if(cktr==0) (*si).id=       stoi(in_line);
  57.             if(cktr==1) (*si).surname= in_line;
  58.             if(cktr==2) (*si).name=     in_line;
  59.             if(cktr==3) (*si).year=     in_line;
  60.             if(cktr==4) (*si).taken=    stoi(in_line);
  61.             if(cktr==5) (*si).grad=     stoi(in_line);
  62.             if(cktr==6) (*si).major=    in_line;
  63.             if(cktr==7) (*si).minor=    in_line;
  64.             ++cktr;
  65.         }
  66.  
  67.         vTmp.emplace_back(*si); //could also receive raw values w/o object or constructor (0,"blah, 0.1,'x',....)
  68.  
  69.         cout<<vTmp.at(rktr).year<<endl;
  70.         delete si;
  71.         rktr++;
  72.     }
  73.     return vTmp;
  74. }
Add Comment
Please, Sign In to add comment