2

I'm trying to read data from a csv file into a vector of structs each containing various values from a football game (offensive team, quarter, down, yards to go, play desc, etc). I'm trying to use stringstream to convert strings to ints but i'm returning junk data.

Data d;  //structs
vector<Data> TeamData;  //vector of structs
string s;
istringstream iss( s );

ifstream myfile;
myfile.open("CSV file here");  //open CSV file


while (  !myfile.eof()  )
{
getline (myfile, d.gameid, ',');  //read to comma, store in d.gameid

getline (myfile, s, ',');  //read to comma
iss >> d.qtr;             //use stringstream to store into d.qtr

repeat for remaining values . . . 

The cvs file looks similar to this if you're wondering:

20070906_NO@IND,1,47,25,IND,NO,1,10,31,(2:25) J.Addai up the middle to NO 27 for 4 yards (S.Fujita).,0,0,2007
20070906_NO@IND,1,46,42,IND,NO,2,6,27,(1:42) P.Manning pass deep left to M.Harrison for 27 yards TOUCHDOWN.,0,0,2007

My program returns data like this when i try to output everything of relevance:

Game ID: 20070906_NO@IND
Offensive team: IND
Quarter: 7077994
Down: 4696320
To go: 4670480
Play: (2:25) J.Addai up the middle to NO 27 for 4 yards (S.Fujita).

Game ID: 20070906_NO@IND
Offensive team: IND
Quarter: 7077994
Down: 4696320
To go: 4670480
Play: (1:42) P.Manning pass deep left to M.Harrison for 27 yards TOUCHDOWN.
GeorgeCostanza
  • 395
  • 1
  • 6
  • 19

2 Answers2

2

I think you should look at my answer for 'reading floats' Instead of parsing on whitespace parse on commas.

Using ifsstream to read floats

Community
  • 1
  • 1
DannyK
  • 1,342
  • 16
  • 23
0

istringstream copies the string you pass it in the constructor, so changes you make to the string following that won't have any effect on the stream. You should construct a new stream, or call the istringstream:str() method to supply a new string, every time the string changes.

getline (myfile, s, ',');  //read to comma
iss.str(s);                // supply new string to stream
iss >> d.qtr;              //use stringstream to store into d.qtr
Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79