This is an example of how to read a CSV file in C++, the while loop and the struct will need to be changed according to how your CSV file is set up. In mine I only require the name and id so use two getlines in the while loop. This most likely could be optimised in some way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
/* The CSV data john, 1 paul, 2 frank, 3 sarah, 4 jones, 5 jack, 6 */ #include <iostream> #include <sstream> #include <fstream> #include <string> using namespace std; struct employees { string name; int id; }; int main () { employees emp[6]; //array of employee structs employees employee; //temp employee struct for use in the while loop ifstream inFile("test.csv"); //our file string line; int linenum = 0; while (getline (inFile, line)) { istringstream linestream(line); string item; //use this to get up to the first comma getline(linestream, item, ','); employee.name = item; //convert to a string stream and then put in id. getline(linestream, item, ','); stringstream ss(item); ss >> employee.id; //add the new employee data to the database emp[linenum] = employee; linenum++; } //output the employee data. for(int i = 0; i < 6; i++) { cout << "name: " << emp[i].name << " id: " << emp[i].id << endl; } return 0; } |
Questions? Comments?