Pagini recente » Cod sursa (job #2280744) | Cod sursa (job #1189786) | Cod sursa (job #537724) | Cod sursa (job #1806369) | Cod sursa (job #1355912)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int getNextKeyIndex(string line, int index) {
int i, length = line.length();
if (index >= length)
return -1;
for (i = index; i < length && line[i] != '"'; ++i);
if (i == length)
return -1;
return i + 1;
}
int getKeyLength(string line, int index) {
int i, length = line.length();
for (i = index; i < length && line[i] != '"'; ++i);
return i - index;
}
int getNextValueIndex(string line, int index) {
int i, length = line.length();
if (index >= length)
return -1;
for (i = index; i < length && !(line[i] == '"' || isdigit(line[i])); ++i);
if (i == length)
return -1;
if (line[i] == '"') ++i;
return i;
}
int getValueLength(string line, int index) {
int i, length = line.length();
bool isNumericalValue = true;
if (index > 0 && line[index - 1] == '"')
isNumericalValue = false;
if (isNumericalValue)
for (i = index; i < length && isdigit(line[i]); ++i);
else
for (i = index; i < length && line[i] != '"'; ++i);
return i - index;
}
int getNextIndex(string line, int index, int type) {
if (type == 0)
return getNextKeyIndex(line, index);
else
return getNextValueIndex(line, index);
}
int getLength(string line, int index, int type) {
if (type == 0)
return getKeyLength(line, index);
else
return getValueLength(line, index);
}
int buildCsvHeader(ifstream & fin, ofstream & fout) {
string line, firstKey;
int counter = 0;
bool finished = false;
while (getline(fin, line) && !finished) {
//cout << "linia citita: " << line << endl;
int index = getNextIndex(line, 0, counter % 2);
while (index != -1) {
int length = getLength(line, index, counter % 2);
string currentString = line.substr(index, length);
//cout << "currentString: " << currentString << endl;
if (counter == 0)
firstKey = currentString;
else if (firstKey == currentString) {
finished = true;
break;
}
if (counter % 2 == 0)
fout << currentString << ",";
++counter;
index = getNextIndex(line, index + length + 1, counter % 2);
}
}
fout << '\n';
return counter / 2;
}
void buildCsvContent(ifstream & fin, ofstream & fout, int elements) {
int counter = 0;
string line;
fin.clear();
fin.seekg(0);
while (getline(fin, line)) {
//cout << "linia citita: " << line << endl;
int index = getNextIndex(line, 0, counter % 2);
while (index != -1) {
int length = getLength(line, index, counter % 2);
string currentString = line.substr(index, length);
//cout << "current string: " << currentString << \;
if (counter % 2 == 1)
fout << currentString << ",";
++counter;
if (counter == 2 * elements) {
counter = 0;
fout << '\n';
}
index = getNextIndex(line, index + length + 1, counter % 2);
}
}
}
int main() {
ifstream fin ("convertor.in");
ofstream fout("convertor.out");
int elements = buildCsvHeader(fin, fout);
buildCsvContent(fin, fout, elements);
fin.close();
fout.close();
return 0;
}