C ++如何解析这个字符串

时间:2012-07-25 09:34:07

标签: c++

我得到了一小块需要解析的代码

我只想要像

这样的值

长名(短名),如欧元(EUR)或英镑(GBP)

并以这种方式使用C ++将其输出到file.txt中

欧元(EUR)
英镑(GBP)

{
        "shortname": "EUR",
        "longname": "Euro",
        "users":  "Austria,Belgium,Cyprus,Finland,Helsinki,France,Paris,Germany,Berlin,Greece,Athens,Ireland,Dublin,Italy,Rome,Milan,Pisa,Luxembourg,Malta,Netherlands,Portugal,Sl$
                "alternatives": "ewro,evro",
        "symbol": "€",
        "highlight": "1"
    },
    {
        "shortname": "GBP",
        "longname": "British Pound",
        "users":  "United Kingdom,UK,England,Britain,Great Britain,Northern Ireland,Wales,Scotland,UK,Isle of Man,Jersey,Guernsey,Tristan da Cunha,South Georgia and the South San$
        "alternatives": "Quid,Pound Sterling,Sterling,London,Cardiff,Edinburgh,Belfast",
        "symbol": "£",
        "highlight": "1"
    },

3 个答案:

答案 0 :(得分:2)

这是JSON。你最好使用解析器。我建议你jsonCpplink

答案 1 :(得分:0)

您可以使用lex和yacc。这样做的好处是没有外部库依赖。

答案 2 :(得分:0)

我建议你http://www.boost.org/doc/libs/1_50_0/doc/html/property_tree.html

使用示例。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <sstream>
#include <iostream>

int main()
{
   using namespace boost::property_tree;
   std::string s = "{\
        \"shortname\": \"EUR\",\
        \"longname\": \"Euro\",\
        \"users\":  \"Austria,Belgium,Cyprus,Finland,Helsinki,France,Paris,Germany,\
        Berlin,Greece,Athens,Ireland,Dublin,Italy,Rome,Milan,Pisa,Luxembourg,Malta,Netherlands,Portugal\",\
        \"alternatives\": \"ewro,evro\",\
        \"symbol\": \"€\",\
        \"highlight\": \"1\"\
    }";
    std::stringstream ss(s);
    ptree pt;
    json_parser::read_json(ss, pt);
    std::string short_n = pt.get<std::string>("shortname");
    std::string long_n = pt.get<std::string>("longname");
    std::cout << long_n << "(" << short_n << ")" << std::endl;
}

http://liveworkspace.org/code/7b9bf87f128a2fe42d606305f4411771