views:

338

answers:

2

I seem to be having a problem with extracting data from a stringstream. The start of my extraction seems to be missing the first two characters.

I have something similar to the following code:

    std::stringstream ss(
 std::stringstream::in |
 std::stringstream::out
 );

    bool bValid;
    double dValue;
    double dTime;

    for( (int i = 0; i < 5; i++ )
    {
        bValid = getValid();
        dValue = getValue();
        dTime = getTime();

        // add data to stream
        ss << bValid;
        ss << dValue;
        ss << dTime;
    }

 int strsize = ss.str().size();
 char* data = new char[strsize];
 std::strcpy(data, ss.str().c_str());

    // then do stuff with data
    // ...... store data in an Xml Node as CDATA

    // read data back
    std::stringstream ssnew( std::stringstream in | std::stringstream out );
    ss.clear();
    ss << getCharData(); // returns a char* and puts it in stream.

    for( int i = 0; i < 5; i++ )
    {
        ssnew >> bValid;  // do something with bValid
        ssnew >> dValue;  // do something with dValue
        ssnew >> dTime;   // do something with dTime
    }

I am having a problem that when I use the extraction operator when reading data from "ssnew" it seems to skip the first two characters. In the debugger, for example, it is showing that the stringstream has "001.111.62.2003... etc". However, after the first "ssnew >> bValid" bValid becomes "true" and dValue becomes "0.111" and dTime becomes "0.62" indicating that the first two zeros in the stream are being ignored. Why isn't it starting at the beginning of the stream?

Cheers, Seth

+2  A: 

Try:

    // add data to stream
    ss << bValid << " ";
    ss << dValue << " ";
    ss << dTime << " ";
Pukku
that worked! but shouldn't it have worked the other way?
Seth
No, it shouldn't have. To understand why, suppose you do something like int x = 1, y = 11, z = 111; ss << x << y << z; -- this results in the string "111111", and the stream has no way of telling how to extract x, y and z as you'd like (as opposed to the other possibilities). As a matter of fact: given just that string, a human being could not tell either. It really is just a plain string we're talking about here; there are no delimiters to separate the fields, unless you explicitly write some.
Pukku
To elaborate, the reason it doesn't work is bools are sometimes treated as (usually 8-bit) integers, not single characters. So as Pukku said, when reading the string looking for "integers" it is impossible to tell where one stops and another starts without spaces or some other deliminator.
SoapBox
A: 

The reason your original code didn't work is that the extraction was greedy, so ssnew >> bValid gobbled up the "001".

Note that strstream is deprecated in favor of stringstream.

outis