Reputation: 1148
I'm getting random numbers after running the line convert >> quarter
, I figure I have to clear stringstream out before I run it to convert again, but how would I go about doing that? And could someone explain what's going on during: (I found this as a solution but don't quite understand it)
stringstream convert(tokens[1]);
convert >> quarter;
-
Play parse(string toParse){
vector<string> tokens;
string play = toParse;
string oName, dName;
int x, quarter, minutes, down, yardstogo, startloc, playdesc;
for(int y=0; y<10; y++){
x = toParse.find(",");
tokens.push_back(toParse.substr(0,x));
toParse = toParse.substr(x+1);
}
stringstream convert(tokens[1]);
convert >> quarter;
convert.str(tokens[2]);
convert >> minutes;
convert.str(tokens[6]);
convert >> down;
convert.str(tokens[7]);
convert >> yardstogo;
convert.str(tokens[8]);
convert >> startloc;
playdesc = findPlay(tokens[9]);
Play a(quarter, minutes, tokens[4], tokens[5], down, yardstogo, startloc, playdesc, play);
return a;
}
Thank you.
Upvotes: 1
Views: 163
Reputation: 680
You could just use the <string>
function stoi (C++11)...
quarter = stoi(tokens[1])
Upvotes: 0
Reputation: 510
You should probably use the atoi() function wich is faster than the stringstream conversion method.
Like so:
quarter = atoi(tokens[1].c_str());
minutes = atoi(tokens[2].c_str());
...
Regards
Upvotes: 0
Reputation: 19879
If you keep doing it this way, you need to call clear() after calling str():
stringstream convert(tokens[1]);
convert >> quarter; // Conversion 1
convert.str(tokens[2]);
convert.clear();
convert >> minutes; // Conversion 2
...
The problem is that the first conversion reads the entire string, which means that it sets the iostate of the stream to eof. Calling str() does not reset the iostate. You have to do it manually.
In your code the iostate is eof on all the later conversions, so no conversion is even attempted.
Upvotes: 1