Cod sursa(job #1346830)

Utilizator GeorgianaElenaDolocan Georgiana Elena GeorgianaElena Data 18 februarie 2015 17:20:39
Problema Convertor Scor 0
Compilator cpp Status done
Runda rosedu_cdl_2015 Marime 2.35 kb
#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>
#include <map>

using namespace std;

string read_the_file()
{
	ifstream t("convertor2.in");
	string str((std::istreambuf_iterator<char>(t)),
	            std::istreambuf_iterator<char>());
	return str;
}

size_t eat_whitespace(string str, size_t pos) {
	while (str[pos] == ' ')
		pos++;
	return pos;
}

void inside_quote (string str, string &keys, size_t &pos, 
	bool quote_closed, bool first_object, ofstream &file) 
{
	quote_closed = !quote_closed;
	if (quote_closed == false) {
		pos++;
		while (str[pos] != '\"') {
			if (first_object == true)
				keys += str[pos];
			else
				file << str[pos];
			pos++;
		}
	}
	quote_closed = true;
}

void return_keys(string str, string &keys, size_t &pos, bool quote_closed, bool first_object, ofstream &file)
{
	inside_quote (str, keys, pos, quote_closed, first_object, file);
	keys += ',';
}

void return_values (string str, string &values, size_t &pos, bool quote_closed, bool first_object, ofstream &file)
{
	pos = eat_whitespace(str, pos + 1);
	while (str[pos] != ',' && str[pos] != '}') {
		if (str[pos] != '\"' && quote_closed == true && str[pos] != ' ' && str[pos] != '\n') {
			if (first_object == true)
				values += str[pos];
			else
				file << str[pos];
		}
		else if (str[pos] == '\"') {
			inside_quote (str, values, pos, quote_closed, first_object, file);
		}
		pos++;
	}
	if (first_object == true)
		values += ',';
	else
		file << ",";
}

void find_pairs(string str)
{
	bool quote_closed = true;
	bool obj_closed = false;

	size_t length = str.length();
	size_t i = 0;

	int obj = 0;
	int pos = 0;

	ofstream out;
	out.open ("convertor.out");

	string keys;
	string values;

	while (i < length) {
		if (obj == 0){
			if (str[i] == '\"') {
				return_keys(str, keys, i, quote_closed, true, out);
			}
			else if (str [i] == ':') {
				return_values(str, values, i, quote_closed, true, out);
			}
		} else {
			if (str [i] == ':') {
					return_values(str, values, i, quote_closed, false, out);
			}
		}
	
		if (quote_closed == true && str[i] == '{') {
			obj_closed = false;
		} 
		if (quote_closed == true && str[i] == '}') {
			if (obj == 0)
				out << keys << endl;
			obj++;
			out << values << endl;
			values.clear();
			obj_closed = true;
			//out << endl;
		} 
		i++;
	}
}

int main()
{
	string str = read_the_file();
	map <string, string> pair;
	find_pairs(str);
}