1

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.

Will Nasby
  • 1,068
  • 2
  • 16
  • 39
  • How to clear a stringstream (extremely searchable): http://stackoverflow.com/questions/20731/in-c-how-do-you-clear-a-stringstream-variable – chris Sep 17 '13 at 00:43
  • You don't need to clear it because you're reinitializing it with `convert.str(...)`. – Barmar Sep 17 '13 at 00:45
  • I was hoping for an explanation on top of that, Chris. Barmar, do you know what I would get bad values then? Quarter and minutes are both ints, when I convert the string of quarter to an int, it's successful, when I convert minutes, I get a very large number. – Will Nasby Sep 17 '13 at 00:47
  • What are you calling the function with? – David G Sep 17 '13 at 00:49
  • PlayList.push_back(parse(line)); – Will Nasby Sep 17 '13 at 00:50

3 Answers3

1

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.

David Norman
  • 19,396
  • 12
  • 64
  • 54
0

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

Oli_G
  • 460
  • 3
  • 17
0

You could just use the <string> function stoi (C++11)...

quarter = stoi(tokens[1])
erlc
  • 652
  • 1
  • 6
  • 11