这只是使用 stl 解析响应字符串的粗略实现,但您可以将其用作进一步处理的起点。如果您可以使用任何正则表达式(例如增强::正则表达式 http://www.boost.org/doc/libs/1_49_0/libs/regex/doc/html/index.html)这个解析可以更简单,但是你也可以使用特定的 json 解析器,所以忘记这个;)
#include <iostream>
#include <sstream>
#include <string>
const char* response = "\
\
{\
\"Result\": \"1\",\
\"gs\":\"0\",\
\"ga\":\"0\",\
\"la\":\"0\",\
\"lb\":\"0\",\
\"lc\":\"0\",\
\"ld\":\"0\",\
\"ex\":\"0\",\
\"gd\":\"0\"\
}";
int main(int argc, char* argv[])
{
std::stringstream ss(response); //simulating an response stream
const unsigned int BUFFERSIZE = 256;
//temporary buffer
char buffer[BUFFERSIZE];
memset(buffer, 0, BUFFERSIZE * sizeof(char));
//returnValue.first holds the variables name
//returnValue.second holds the variables value
std::pair<std::string, std::string> returnValue;
//read until the opening bracket appears
while(ss.peek() != '{')
{
//ignore the { sign and go to next position
ss.ignore();
}
//get response values until the closing bracket appears
while(ss.peek() != '}')
{
//read until a opening variable quote sign appears
ss.get(buffer, BUFFERSIZE, '\"');
//and ignore it (go to next position in stream)
ss.ignore();
//read variable token excluding the closing variable quote sign
ss.get(buffer, BUFFERSIZE, '\"');
//and ignore it (go to next position in stream)
ss.ignore();
//store the variable name
returnValue.first = buffer;
//read until opening value quote appears(skips the : sign)
ss.get(buffer, BUFFERSIZE, '\"');
//and ignore it (go to next position in stream)
ss.ignore();
//read value token excluding the closing value quote sign
ss.get(buffer, BUFFERSIZE, '\"');
//and ignore it (go to next position in stream)
ss.ignore();
//store the variable name
returnValue.second = buffer;
//do something with those extracted values
std::cout << "Read " << returnValue.first<< " = " << returnValue.second<< std::endl;
}
}