2

我似乎在从字符串流中提取数据时遇到问题。我提取的开始似乎缺少前两个字符。

我有类似于以下代码的内容:

    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
    }

我有一个问题,当我从“ssnew”读取数据时使用提取运算符时,它似乎跳过了前两个字符。例如,在调试器中,显示字符串流具有“001.111.62.2003...等”。但是,在第一个“ssnew >> bValid”之后,bValid 变为“true”,dValue 变为“0.111”,dTime 变为“0.62”,表明流中的前两个零被忽略。为什么它不是从流的开头开始?

干杯,赛斯

4

2 回答 2

2

尝试:

    // add data to stream
    ss << bValid << " ";
    ss << dValue << " ";
    ss << dTime << " ";
于 2009-07-20T06:46:54.920 回答
0

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.

于 2009-07-20T07:07:07.420 回答