It seems the easiest approach to read the tab separated file is to define a trivial class cell
derived from std::string
with an input operator simply using std::getline()
with the stream, the call which is treated as a std::string
, and using '\t'
as the "line terminator". With that, each line can be seen as a sequence of cell
s which are inserted into a std::vector<std::string>
which is itself just added to a std::vector<std::vector<std::string>>
. Below is the code together with a simple output of the result. The output requires C++11, everything else should compile with C++03, too.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
struct cell: std::string {};
std::istream& operator>> (std::istream& in, cell& c) {
return std::getline(in, c, '\t');
}
int main()
{
std::vector<std::vector<std::string>> values;
std::ifstream fin("in.csv");
for (std::string line; std::getline(fin, line); )
{
std::istringstream in(line);
values.push_back(
std::vector<std::string>(std::istream_iterator<cell>(in),
std::istream_iterator<cell>()));
}
for (auto const& vec: values) {
for (auto val: vec) {
std::cout << val << ", ";
}
std::cout << "\n";
}
}