Cod sursa(job #1357223)

Utilizator CapitanulCeapaRozArsenescu Mihai-Catalin CapitanulCeapaRoz Data 23 februarie 2015 20:30:13
Problema Convertor Scor 60
Compilator cpp Status done
Runda rosedu_cdl_2015 Marime 2.6 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;
	// Stream for parsing	
	ifstream in("convertor.in");	
	// Saving unique keys in order of appearance
	vector<string> unique_keys;		
	// Map to save keys and their corresponding vector of values(in order)
	unordered_map<string, string > map;
	in.get(c);
	// firstly i parse the first keys-values group and get unique keys
	while (c != ']') {		
		// if i find a key
		if (c == '"') {		
			// i parse it
			stringstream key;	
			while (in.peek() != '"') {
				in.get(c);
				key << c;
			}
			// ignore closing quotation mark
			in.get(c);
			in.get(c);		
			// start looking for it's associated value
			stringstream value; 
			while (c == ':' || c == ' ') {
				in.get(c);
			}
			// if value is enclosed in quotation marks
			if (c == '"') {			
				in.get(c);
				while (c != '"') {
					value << c;
					in.get(c);
				}
			}
			// if it's a number
			else {					
				while (c != ',' && c != ' ') {
					value << c;
					in.get(c);
				}
			}
			// insert key and value
			map.insert(pair <string, string>(key.str(), value.str()));
			unique_keys.push_back(key.str());
		}
		// break after first group of keys-values (enclosed in accolades)
		if (c == '}')	break;
		in.get(c);
	}
	// writing first set of keys-values
	ofstream out("convertor.out");
	// writing keys
	for (auto& unique_key : unique_keys) {
		out << unique_key << ",";
	}
	out << endl;
	// writing values
	for (auto& unique_key : unique_keys) {
		out << map.at(unique_key) << ",";
	}
	out << endl;
	// index of key whose value will be parsed
	// index will be reset at 0 after last key
	// i look only for values (after ':')
	unsigned int index = 0;		
	while (c != ']') {				
		if (c == ':') {			
			// i parse the value
			stringstream value;		
			while (c == ':' || c == ' ') {
				in.get(c);
			}
			// if value is enclosed in quotation marks
			if (c == '"') {			
				in.get(c);
				while (c != '"') {
					value << c;
					in.get(c);
				}
			}
			// if it's a number
			else {					
				while (c != ',' && c != ' ') {
					value << c;
					in.get(c);
				}
			}				
			// i write the value and newline if needed
			out << value.str() << ",";
			index++;				
			if (index == unique_keys.size()) {
				index = 0;
				out << endl;
			}
		}
		in.get(c);
	}
	out.close();
	in.close();
	return 0;
}