Advertisement
Rochet2

Parsing stuff

Dec 21st, 2012
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <stdio.h>
  3. #include <map>
  4. #include <string>
  5. #include <iostream>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. map<string, string> GetArgMap(string text)
  10. {
  11.     map<string, string> DataMap;
  12.     size_t pos1 = 0;
  13.     while (true)
  14.     {
  15.         pos1 = text.find('"', pos1);
  16.         if(pos1 == string::npos)
  17.             break;
  18.         size_t pos2 = text.find('"', ++pos1);
  19.         if(pos2 == string::npos)
  20.             break;
  21.         string Key = text.substr(pos1, pos2-pos1);
  22.         if(Key.empty())
  23.             break;
  24.  
  25.         pos1 = text.find(':', pos1);
  26.         if(pos1 == string::npos)
  27.             break;
  28.         pos2 = text.find(',', ++pos1);
  29.         if(pos2 == string::npos)
  30.         {
  31.             pos2 = text.find('}', pos1);
  32.             if(pos2 == string::npos)
  33.                 break;
  34.         }
  35.         string Value = text.substr(pos1, pos2-pos1);
  36.         if(Value.empty())
  37.             break;
  38.  
  39.         Value.erase(remove(Value.begin(), Value.end(), '"'), Value.end());
  40.         DataMap[Key] = Value;
  41.         pos1 = pos2;
  42.     }
  43.     return DataMap;
  44. }
  45.  
  46. int main()
  47. {
  48.     string text = "{\"countryId\":17,\"maxMembers\":20,\"name\":\"Resolution\",\"goldValue\":200,\"totalDamage\":154295731,\"militaryUnitType\":\"Regular\"}"; // test text
  49.  
  50.     map<string, string> DataMap = GetArgMap(text); // get the arguments
  51.  
  52.     for(map<string, string>::iterator it = DataMap.begin(); it != DataMap.end(); ++it) // test print all arguments
  53.     {
  54.         cout << it->first << " " << it->second << endl;
  55.     }
  56.     cout << endl;
  57.    
  58.     cout << DataMap["name"] << endl; // test print name argument
  59.  
  60.     cin.get(); // pausing the console
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement