user1548465
user1548465

Reputation: 65

C++ How to parse this string out

I got a small chunk of code that i need to parse out

I just want the value like

longname (shortname) such as Euro (EUR) or maybe Bristish Pound (GBP)

and output it into a file.txt using C++ in this way

Euro (EUR)
British Pound (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"
    },

Upvotes: 1

Views: 192

Answers (3)

ForEveR
ForEveR

Reputation: 55887

I suggest you http://www.boost.org/doc/libs/1_50_0/doc/html/property_tree.html

example of usage.

#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

Upvotes: 0

doron
doron

Reputation: 28892

You can use lex and yacc. This has the advantage that there is no external library dependency.

Upvotes: 0

Andrew
Andrew

Reputation: 24846

It's JSON. You'd better use a parser. I suggest you jsonCpp (link)

Upvotes: 2

Related Questions