Cod sursa(job #1350050)

Utilizator cernat.catallinFMI Cernat Catalin Stefan cernat.catallin Data 20 februarie 2015 17:16:31
Problema Convertor Scor 100
Compilator cpp Status done
Runda rosedu_cdl_2015 Marime 2.07 kb
#include <fstream>
using namespace std;

ifstream in("convertor.in");
ofstream out("convertor.out");

char *text;
size_t length;
size_t at;

void read() {
	in.seekg(0, in.end);
	length = in.tellg();
	in.seekg(0, in.beg);
	text = new char[length];
	in.read(text, length);
}

void in_object() {
	char buffer[2048];
	int pos = 0;

	while (true) {
		// skip attribute name
		while (text[at] != ':' && text[at] != '}') ++at;
		++at;
		if (text[at - 1] == '}') break;

		while (text[at] != '\"' && !('0' <= text[at] && text[at] <= '9')
			&& text[at] != '-') ++at;

		//get attribute value

		// value is an integer
		// signed integer
		if (text[at] == '-') {
			buffer[pos] = text[at];
			++pos;
			++at;
		}

		if ('0' <= text[at] && text[at] <= '9') {
			while ('0' <= text[at] && text[at] <= '9') {
				buffer[pos] = text[at];
				++at;
				++pos;
			}
			buffer[pos] = '\0';
		}
		// value is a 'string'
		else {
			++at;
			while (text[at] != '\"') {
				buffer[pos] = text[at];
				++at;
				++pos;
			}
			buffer[pos] = '\0';
		}

		out << buffer << ',';
		pos = 0;
	}
	out << '\n';
}

void get_attributes() {
	char buffer[2048];
	int pos = 0;

	while (true) {
		// get attribute name
		while (text[at] != '\"') ++at;
		++at;
		while (text[at] != '\"') {
			buffer[pos] = text[at];
			++at;
			++pos;
		}
		buffer[pos] = '\0';
		out << buffer << ',';
		pos = 0;

		// check if there are more atttributes
		while (text[at] != ',' && text[at] != '}') ++at;
		if (text[at] == '}') break;
	}
	out << '\n';
}

void solve() {
	// check for at least one object with at leat one attribute
	bool found = false;
	while (at < length) {
		if (text[at] == '{') {
			while (at < length) {
				if (text[at] == '}') break;
				if (text[at] == '\"') {
					found = true;
					break;
				}
				++at;
			}
			break;
		}
		++at;
	}
	if (!found) return;

	at = 0;
	get_attributes();
	at = 0;
	while (at < length) {
		if (text[at] == '{')
			in_object();
		++at;
	}
}

int main() {
	read();
	solve();
	return 0;
}