Cod sursa(job #1359597)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 24 februarie 2015 23:53:50
Problema Convertor Scor 100
Compilator cpp Status done
Runda rosedu_cdl_2015 Marime 2.56 kb
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string line, keyArray, valueArray;
    /* index - pozitia curenta in sir
       left, right - indici folositi la determinarea subsirului corespunzator unei chei/valori */
    string::size_type index, left, right;
    bool firstObject = true, key = false;

    ifstream f("convertor.in");
    ofstream g("convertor.out");
    while (getline(f, line))
    {
        do
        {
            if (!key) // cautam o cheie sau }
            {
                index = line.find_first_of("}\"");
                if (index != string::npos)
                {
                    if (line[index] == '}') // } - am incheiat citirea unui obiect
                    {
                        if (firstObject)
                        {
                            g << keyArray << '\n';
                            firstObject = false; // dupa primul obiect avem lista cheilor, deci nu ne mai atingem de ea
                        }
                        left = right = index;
                        g << valueArray << '\n';
                        valueArray = ""; // golim string-ul cu valori pentru conservarea memoriei
                    }
                    else
                    {
                        left = index;
                        right = line.find('"', left + 1);
                        if (firstObject)
                            keyArray += line.substr(left + 1, right - left - 1) + ',';
                        key = true;
                    }
                    index = right + 1;
                }
            }
            else // cautam o valoare
            {
                index = line.find_first_of("0123456789\"");
                if (index != string::npos)
                {
                    left = index;
                    if (line[index] >= '0' && line[index] <= '9')
                    {
                        right = line.find_first_not_of("0123456789", left + 1);
                        valueArray += line.substr(left, right - left) + ',';
                        index = right;
                    }
                    else
                    {
                        right = line.find('"', index + 1);
                        valueArray += line.substr(left + 1, right - left - 1) + ',';
                        index = right + 1;
                    }
                    key = false;
                }
            }
            if (index != string::npos)
                line = line.substr(index);
        } while (index != string::npos);
    }

    f.close();
    g.close();
    return 0;
}