Cod sursa(job #1350524)

Utilizator ShardamaKaTache Alexandru Marius ShardamaKa Data 20 februarie 2015 20:26:41
Problema Convertor Scor 90
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.77 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void creare_string(char *string, FILE *input)
{
    char c;
    int i = 0;
    c = fgetc(input);
    while(c != EOF)
    {
        string[i] = c;
        c = fgetc(input);
        i++;
    }
    string = (char*)realloc(string, i);
}
void stergere_spatii(char *string)
{
    int cont = 0;
    char *dst, *src;
    for(dst = src = string; *src != '\0'; src++)
    {
        if(*src == '"')
        {
            cont++;
        }
        if(cont % 2 == 1)
        {
            *dst = *src;
            dst++;
        }
        if(cont % 2 == 0)
        {
            *dst = *src;
            if(*dst != ' ')
            {
                dst++;
            }
        }
    }
    *dst = '\0';
}
void stergere_trash(char *string)
{
    char *src, *dst;
    for(src = dst = string; *src != '\0'; src++)
    {
        *dst = *src;
        if( *dst != '[' && *dst != '{' && *dst != '}' && *dst != ']' && *dst != '\n' && *dst != '"' )
        {
            dst++;
        }
    }
    *dst = '\0';
}
int numar_chei(char *string)
{
    int i, nr = 0;
    for(i = 0; i < strlen(string); i++)
    {
        if(string[i] == ':')
        {
            nr++;
        }
        if(string[i] == '}')
        {
            break;
        }
    }
    return nr;
}
void introducere(char *string, int nr_chei, FILE *output)
{
    char *token, *aux;
    aux = malloc(sizeof(char) * strlen(string));
    strcpy(aux, string);
    int i, nr = 0, nr_chei_aux = 0;
    token = strtok(string, ",:");
    while(token != NULL)
    {
        if(nr % 2 == 0)
        {
            nr_chei_aux++;
            fprintf(output, "%s,", token);
        }
        if(nr_chei_aux == nr_chei)
        {
            fprintf(output, "%s", "\n");
            break;
        }
        nr++;
        token = strtok(NULL, ",:");
    }
    nr = 0;
    nr_chei_aux = 0;
    token = strtok(aux, ",:");
    while(token != NULL)
    {
        if(nr % 2 == 1)
        {
            nr_chei_aux++;
            fprintf(output, "%s,", token);
        }
        if(nr_chei_aux == nr_chei)
        {
            nr_chei_aux = 0;
            fprintf(output, "%s", "\n");
        }
        nr++;
        token = strtok(NULL, ",:");
    }
    free(aux);
}
int main()
{
    FILE *input, *output;
    char *string;
    int nr_chei;
    input = fopen("convertor.in", "rt");
    output = fopen("convertor.out", "wt");
    string = (char*)malloc(sizeof(char) * 1000000);
    creare_string(string, input);
    nr_chei = numar_chei(string);
    stergere_spatii(string);
    stergere_trash(string);
    introducere(string, nr_chei, output);

    free(string);
    fclose(input);
    fclose(output);
    return 0;
}