Cod sursa(job #1355851)

Utilizator CapitanulCeapaRozArsenescu Mihai-Catalin CapitanulCeapaRoz Data 22 februarie 2015 23:37:06
Problema Convertor Scor 50
Compilator cpp Status done
Runda rosedu_cdl_2015 Marime 2.12 kb
// convertor.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>

using namespace std;


int main(int argc, char* argv[])
{
	int json_entries = 0;
	char c;
	ifstream in("convertor.in");	// Stream for parsing	
	vector<string> unique_keys;		// Saving unique keys in order of appearance
	unordered_map<string, vector<string> > map;
	in.get(c);
	while (c != ']') {		
		if (c == '"') {				// if i find a key
			stringstream key;	// i parse it
			string ceva;
			while (in.peek() != '"') {
				in.get(c);
				key << c;
				ceva = key.str();
			}
			in.get(c);
			in.get(c);				// ignore closing quotation mark
			stringstream value; // start looking for it's associated value
			while (c == ':' || c == ' ') {
				in.get(c);
			}
			ceva = string();
			if (c == '"') {			// if value is enclosed in quotation marks
				in.get(c);
				while (c != '"') {
					value << c;
					in.get(c);
					ceva = key.str();
				}
			}
			else {					// if it's a number
				while (c != ',' && c != ' ') {
					value << c;
					in.get(c);
				}
			}
			if (map.find(key.str()) == map.end()) {
				unique_keys.push_back(key.str());
				map.insert(pair<string, vector<string> >(key.str(), vector<string>()));
				map.at(key.str()).push_back(value.str());
			}						// if key not found in map i insert it
			else {
				map.at(key.str()).push_back(value.str());
			}						// if key already exists in map
		}
		in.get(c);
	}
	if (unique_keys.size() != 0) {	// proceed only if we have at least one key
		ofstream out("convertor.out");
		json_entries = map.at(unique_keys.at(0)).size();
		for (auto& unique_key : unique_keys) {
			out << unique_key << ",";
		}							// writing the keys
		out << endl;
		for (int entry = 0; entry < json_entries; entry++) {
			for (auto& unique_key : unique_keys) {
				out << map.at(unique_key).at(entry) << ",";
			}
			if (entry != json_entries - 1) {
				out << endl;
			}
		}							// writing the entries
		out.close();
	}
	in.close();
	return 0;
}