stringstream可以解析这样的东西吗?

jma*_*erx 0 c++ stl

我有这样的数据字符串:

b = bool
i = int
sINT: = string whose length is INT followed by a : then the string
m = int message id.
Run Code Online (Sandbox Code Playgroud)

例:

m133s11:Hello Worldi-57989b0b1b0
Run Code Online (Sandbox Code Playgroud)

这将是:

Message ID 133
String 'Hello World' length 11
int -57989
bool false
bool true
bool false
Run Code Online (Sandbox Code Playgroud)

STL中有什么东西可以轻松解析这个吗?

Mar*_*ork 6

是的:

std::stringstream   data("m133s11:Hello Worldi-57989b0b1b0");
while(parse(data))
{
   // 1 item was correctly removed from the stream
}

std::istream& parse(std::istream& data)
{
    char format;
    data >> format;

    switch(format)
    {
        case 'i':   int value;  data >> value;break;
        case 'm':   int id;     data >> id;   break;
        case 'b':   bool value; data >> value; break;
        case 's':
        {
            std::size_t   size;
            char          x = '0';
            data >> size >> x;
            if ((!data) || (x != ':'))
            {   // Something went wrong
                data.setstate(std::ios_base::iostate::badbit);
            }
            else
            {
                std::string  value(size, ' ');
                data.read(&value[0], size);
            }
            break;
        }
    }
    return data;
}
Run Code Online (Sandbox Code Playgroud)