djdangerousdick djdangerousdick - 10 months ago 53
C++ Question

take multiple lines of input,split at comma, store each line into string array

Here is an example of the type of input I would be working with:
(coming from standard input)

Archery,M,TEAM,Archery,Lord's Cricket Ground,1. GOLD,team ITA,Italy
Archery,M,TEAM,Archery,Lord's Cricket Ground,2. SILVER,team USA,United States
Archery,M,TEAM,Archery,Lord's Cricket Ground,3. BRONZE,team KOR,South Korea
Cycling,M,IND,Road,Regent's Park,1. GOLD,Aleksander Winokurow,Kazakhstan
Cycling,M,IND,Road,Regent's Park,2. SILVER,Rigoberto Uran,Colombia
Cycling,M,IND,Road,Regent's Park,3. BRONZE,Alexander Kristoff,Norway
Fencing,F,IND,Foil,ExCeL,1. GOLD,Elisa Di Francisca,Italy

As the title suggests I want to take each line, split it a the comma, and store each one of those strings into an array (or vector of strings). THEN I want to take each item in the array and use it as parameters for a function. I know how to read multiple lines and how to split a string but when I put those things together it's not really working out for me.

my line of thinking:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;
int main()
string line;
stringstream ss(line);

while (line != "InsertionEnd") {

vector<string> array;
getline(ss, line, ',');

so after I get my array i want to use an addItem function that I made which just creates an athlete structure (takes 8 parameters). like so:

myTable.addItem("Archery","M","TEAM","Archery","Lord's Cricket Ground","1. GOLD","team ITA","Italy");

Am I on the right track ? or is this completely off base?? thanks.

note: I have tested the addItem functions and it works when you just type in the parameters yourself.

qxz qxz
Answer Source

Here is a solution that properly loops through the input, splitting each line and calling addItem with the extracted tokens:

string line;
while (getline(cin, line)) { // for each line...
    if (line == "InsertionEnd") break;

    // split line into a vector
    vector<string> array;
    stringstream ss(line);
    string token;
    while (getline(ss, token, ',')) { // for each token...

    // use the vector