-1

I have string like this:

     ab   cd   ef   gh
1    4    2    9    9
9    1    0    4    1.5
1    4    2    9.0

It may start with \t (or other delimiter). If it starts with \t - it means that result[0][0] = "".

How can I convert this to 2-dimensional array of string?

Im total newbie in linux c++.

Kamil
  • 13,363
  • 24
  • 88
  • 183

1 Answers1

0

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 cells 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";
    }
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380