Help with CSV!
Hi, please can someone explain how I would take a text file containing comma-separated variables and put it into an array in C++ so that I can easily work with the data. The CSV file has 3000 rows and about 5 columns, and I'd like to keep the array with the same number of rows and columns.
I'm new to C++, so I hope that this question makes sense. If not could someone please explain what would be the best way of getting this data into C++ so that I can work with it easily?
Thanks in advance for your help!
fscanf is one partial solution, although that is more of a C method than a C++ one.
If you want to use C++ tools, use an ifstream to open the file and then use getline to read in each line. You can then use a stringstream with getline to separate each value in each line. The benefit of this is that it will make it easier to handle bad input.
For the array, it sounds like you need an array of objects, so I would make a struct or class that holds the types of data stored in the columns. Then, use a vector instead of an array to hold each row.
Thanks for that, I'm going to get started with it right away. Just one question, what would the elements of the vectors be in this case? Would each element of the vector be one site (so that I have one vector with 3000 elements)? or would I have multiple vectors containing 5 elements (latitude, longitude, slope, aspect, altitude, all of which are doubles)?
Sorry if this seems like an obvious question, I'm just struggling a bit to understand how vectors compare to arrays.
If you know structs or classes, make each element of the vector an instance of that class. You could make it a vector of vectors of doubles, but it makes more sense to combine the five doubles into a struct and just have a single vector.
Think of a vector as the same as an array. You could do the same thing with an array. Either a single array of your struct or class, or a two dimensional array of doubles. If you know you will always have exactly 3000 rows, then an array might even be a better choice. A vector is good for when you're not sure when you compile how big the array will be.