0

I've got a simple CSV file:

name,surname
Joe,Moe
Bob,Rob

In JavaScript I would simply create an array of objects in the following way:

// let's assume the csv file is valid and it was already processed
var csv = ["name", "surname", "Joe", "Moe", "Bob", "Rob"],
    ret = [],
    i, ilen, j, o,
    cols = 2;        

for (i = cols, ilen = csv.length; i < ilen; i += cols) {
    o = {};
    for (j = 0; j < cols; j += 1) {
       o[csv[j]] = csv[i + j];
    }
    ret.push(o);
}

console.log(ret); // [{name: "Joe", surname: "Moe"}, {name: "Bob", surname: "Rob"}]

I'd like to create a vector filled with objects (instances of a class). The class would need to be generated during run-time, the csv file might change.

Could you guide how to achieve this in c++?

Emil A.
  • 3,387
  • 4
  • 29
  • 46
  • That's not a CSV file, the items are separated by whitespace. Nonetheless, the general approach should be to read the file line by line, splitting them into whitespace-separated columns. See [getline](http://www.cplusplus.com/reference/string/string/getline/) to get a line from a file and the question [Splitting a string by whitespace in C++](http://stackoverflow.com/questions/2275135/splitting-a-string-by-whitespace-in-c) for how to split that into items. – John Chadwick Feb 20 '14 at 21:26
  • I know how to split a string, could you let me know how can I create a class dynamically while the program is running? Please assume that the csv input might change – Emil A. Feb 20 '14 at 21:28
  • Look up the `new` operator to allocate objects *dynamically* which means during run-time in the dynamic memory area. – Thomas Matthews Feb 20 '14 at 21:30
  • Ok, but the class would need to exist first and in my case I'd like to create the class during run-time. – Emil A. Feb 20 '14 at 21:34
  • No need to manually generate objects in this case, though - you could have a vector, have a local string, and simply store the string multiple times. Changing your string after storing it will not change strings you've stored because the objects in the vector are by-value, so you can change + store as many times as needed. It is dynamic behind the scenes. – John Chadwick Feb 20 '14 at 21:34
  • I'd like to build something more complex on top of it, it'll be easier for me to take an object oriented approach and I'd like to learn more about it. – Emil A. Feb 20 '14 at 21:48

1 Answers1

1

C++ has no concept of a dynamic type that can be constructed at run-time. You'll have to use collections, like std::vector<std::pair<std::string, std::string>>, which could store a row of (name, value) pairs.

Peter R
  • 2,865
  • 18
  • 19