Newbie here: How do I read csv into a vector of structs? #160
-
I could not find this case among the examples. I don't care to std::cout anything; I just want to fill a vector of structs with, ironically, daily stock data from Yahoo csv files. My struct is,
where,
and I make an std::vector< YahooCSVdaily >. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi - so the API of rapidcsv is more intended to operate directly on columns of data, say get an vector of floats holding all close prices. There are other C++ CSV libraries which provides more low-level access to parsed data and as such are more suitable for populating vectors of custom structs. Having that said, it is certainly possibly to use rapidcsv. One can for example iterate over the rows and build a struct using something like this: #include <iostream>
#include <vector>
#include "rapidcsv.h"
struct Daily
{
std::string m_Date;
float m_Open = 0.0;
float m_High = 0.0;
float m_Low = 0.0;
float m_Close = 0.0;
int m_Volume = 0.0;
float m_AdjClose = 0.0;
};
int main()
{
rapidcsv::Document doc("examples/colrowhdr.csv");
std::vector<Daily> dailys;
const size_t rowCount = doc.GetRowCount();
for (size_t rowIdx = 0; rowIdx < rowCount; ++rowIdx)
{
Daily daily;
daily.m_Date = doc.GetCell<std::string>(0, rowIdx);
daily.m_Open = doc.GetCell<float>(1, rowIdx);
daily.m_High = doc.GetCell<float>(2, rowIdx);
daily.m_Low = doc.GetCell<float>(3, rowIdx);
daily.m_Close = doc.GetCell<float>(4, rowIdx);
daily.m_Volume = doc.GetCell<int>(5, rowIdx);
daily.m_AdjClose = doc.GetCell<float>(6, rowIdx);
dailys.push_back(daily);
}
for (const auto& daily : dailys)
{
std::cout << daily.m_Date << ": " << daily.m_Close << "\n";
}
} Another alternative would be to call Hope this helps. Good luck! |
Beta Was this translation helpful? Give feedback.
Hi - so the API of rapidcsv is more intended to operate directly on columns of data, say get an vector of floats holding all close prices.
There are other C++ CSV libraries which provides more low-level access to parsed data and as such are more suitable for populating vectors of custom structs.
Having that said, it is certainly possibly to use rapidcsv. One can for example iterate over the rows and build a struct using something like this: