March 3, 201115 yr #include <iostream> #include <iomanip> #include <vector> #include <fstream> using namespace std; struct datastring { int studentNum; string studentName; double OB; //outstanding balance }; int main() { int size = 2; vector<datastring> myVec(2); ifstream FI; FI.open("students.dat"); if (FI.fail()) { cerr<<"File failed to open, create it."<<endl; abort(); } FI >> myVec.studentNum; while(!FI.eof()) { cin.ignore(); cin.getline(FI, myVec.studentName); FI >> myVec.OB; if (myVec.size() >= size) { myVec.resize(2*size); } FI >> myVec.studentNum; } cout<<"Works"<<endl; FI.close(); return 0; } The main focus is when I'm trying to read in information from a file into a vector, and it just can't seem to work with my struct. The task is to learn dynamic allocation, and that's why there's a resize function. The rest is cake once I get this resolved. Any help is appreciated. I was going to eat hot dogs for dinner tonight. I think I will settle for cereal. OPEN WIDE HERE COMES THE HELICOPTER.
March 4, 201115 yr http://www.cplusplus.com/reference/stl/vector/ You don't resize vectors as that is handled automatically by the container.You add objects to vectors using push_back or push_front usually. Theres also methods for inserting.myVec.push_back(datastring); You should also consider reading up on the other types of containers since they all have advantages and disadvantages.http://www.cplusplus.com/reference/stl/
March 4, 201115 yr http://pastebin.com/uUsEAEPH #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; struct studentData { int ID; string firstName; string lastName; double outstandingBalance; }; int main() { vector<studentData> vecStudentData; ifstream fileInput; fileInput.open("students.dat", ifstream::in); if(fileInput.fail()) { cout << "File failed to open" << endl; return 1; } studentData temp; while(fileInput.good()) { fileInput >> temp.ID >> temp.firstName >> temp.lastName >> temp.outstandingBalance; vecStudentData.push_back(temp); } fileInput.close(); for(unsigned int i = 0; i < vecStudentData.size(); i++) { cout << i << " " << vecStudentData[i].ID << " " << vecStudentData[i].firstName << " " << vecStudentData[i].lastName << " " << vecStudentData[i].outstandingBalance << endl; } } This assumes a .dat layout with each var seperated by whitespace.eg/ID FIRSTNAME LASTNAME OB ID FIRSTNAME LASTNAME OB...ID FIRSTNAME LASTNAME OB ID FIRSTNAME LASTNAME OB ...ID FIRSTNAME LASTNAME OB ... I hate files :(
Create an account or sign in to comment