Created
October 9, 2014 02:01
-
-
Save giacobo1/6565d8d91bc14cfe1fd9 to your computer and use it in GitHub Desktop.
Problema: “Bagunça das palavras” (Word Scramble - 483)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| // Passa o nome do arquivo com os dados para o main (argv[1]) | |
| // exemplo: | |
| // 1. Compila - gcc main.c -o run | |
| // 2. Rodar - ./run data.in | |
| // Onde data.in eh o arquivo que contem o texto a ser invertido. | |
| int main(int argc, char const *argv[]) { | |
| if ( argc == 2 ) { | |
| FILE *fp = NULL; | |
| // Abre o arquivo; | |
| if ( !(fp = fopen(argv[1], "r")) ) { | |
| printf("Erro ao abrir o arquivo: %s\n", argv[1]); | |
| } | |
| char c = 'a'; | |
| int i = 0; | |
| int j = 0; | |
| // Inicializa uma area de memoria para guardar a string que deve ser invertida; | |
| char* tmp_buffer = (char*)malloc(sizeof(char) * 64); | |
| // Le o arquivo caracter-a-caracter e para ao encontrar a flag de final de arquivo; | |
| while ( (c = fgetc(fp)) > 0 ) { | |
| // Caso nao precise ser invertido, coloca no buffer temporario; | |
| if ( c != ' ' && c != '\n') { | |
| tmp_buffer[i++] = c; | |
| } else if ( c == ' ' ) { // Encontrou espaco, precisa inverter; | |
| for (j = i ; j >= 0 ; j--) { | |
| putchar(tmp_buffer[j]); // Imprime invertido | |
| tmp_buffer[j] = '\0'; // Limpa o buffer | |
| } | |
| putchar(' '); // Imprime o espaco que ele "comeu no teste" | |
| i = 0; | |
| } else if ( c == '\n' ) { | |
| for (j = i ; j >= 0 ; j--) { | |
| putchar(tmp_buffer[j]); // Imprime invertido | |
| tmp_buffer[j] = '\0'; // Limpa o buffer | |
| } | |
| putchar('\n'); // Imprime a quebra de linha que ele "comeu no teste" | |
| i = 0; | |
| } | |
| } | |
| free(tmp_buffer); // Deleta o buffer | |
| fclose(fp); // Fecha o arquivo | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment