0

I have a vector of strings that each equal a table row that I got by reading an excel file. Each row is in the form of:

A1;B1;C1
A2;B2;C2
A3;B3;C3 and so on.

What I would like to do is split the code into each column so that I can evaluate the columns as a vector with the same type of information. That would mean that I would get a vector like this: string vec = ["A1", "A2", "A3"];. This basically means I would have to split the vectors whenever I encounter the ";" character. I wonder if there's an easier way of doing it, instead of a bunch of nested for loops. Also I'm sorry if I'm missing something obvious :P.

NikoD
  • 15
  • 4
  • Sounds like [this](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) is what you want. – NathanOliver Jun 16 '21 at 21:36

1 Answers1

1

I believe this should get you what you want:

string row = "A1;B1;C1";

//initialize StringStream from your string
stringstream ss;
ss.str(row);

//vector to hold strings after split
vector<string> vs;

//used to hold the split string and insert into vector
string splitString;

//push all split strings into vector
while (getline(ss, splitString, ';'))
{
    vs.push_back(splitString);
}  

If you have multiple strings for this, you can just slap a loop on this.

Austin
  • 2,203
  • 3
  • 12
  • 28
  • *just slap a loop on this.* `while (this){}`? – user4581301 Jun 16 '21 at 21:46
  • @Austin thanks for the help, I'll try this tomorrow (pretty late here) and come back to you. – NikoD Jun 16 '21 at 21:49
  • 1
    @user4581301 the OP said "*I have a vector of strings*" - just loop through that vector, calling this code on each string (eg `for(size_t i = 0; i < vec.size(); ++i) { string row = vec[i]; ... }` or `for(string row : vec) { ... }`) – Remy Lebeau Jun 16 '21 at 22:02
  • @Austin ideally I'd want to choose which strings because I will be performing some calculations with the data but I don't think there will be that many vectors that I'll need. But in essence yes, I would want to separate all columns in this case into their own separate vectors. – NikoD Jun 16 '21 at 22:41