or is there any ways for me to only get specific column only without assigning/parsing each column to each variable?
It's not really practical with the CSV format to avoid reading every column, so really what you want to do is basically just discard the columns you do not want, much like you are already doing.
To make it work with an unknown number of columns, you can read into a std::vector
, which is basically a dynamically sized array, so really useful for cases like this.
std::vector<std::string> read_csv_line(const std::string &line)
{
std::vector<std::string> ret;
std::string val;
std::stringstream ss(line);
while (std::getline(ss, val, ','))
ret.push_back(std::move(val));
return ret;
}
...
std::getline(is, line);
auto row = read_csv_line(line);
if (row.size() > 10) // Check each row is expected size!
std::cout << row[0] << ", " << row[10] << std::endl;
else std::cerr << "Row too short" << std::endl;
You can then access the specific columns you want.
or maybe i could get the column by its name?
Assuming your CSV file has a header line, you can read that into say a std::unordered_map<std::string, size_t>
where the value is the column index. Alternatively something like a std::vector
with std::find
.
Note that handling of quoted values, and some other possible CSV features can't be done with a single std::getline
.