Merge branch 'fgets' of UBB/sort into master

This commit is contained in:
Chris Cromer 2018-11-13 12:25:40 -03:00 committed by Gitea
commit fa78806865
1 changed files with 35 additions and 6 deletions

View File

@ -65,6 +65,34 @@ void print_array(int *array, int n) {
fprintf(stdout, "\n\n"); fprintf(stdout, "\n\n");
} }
/**
* Leer el buffer de stdin y guardar el valor si es numerico
* @param variable Donde se guarda el valor del stdin
* @return Retorna 1 si es exitosa ó 0 si falla
*/
int read_buffer(int *variable) {
char buffer[12];
while (1) {
if (fgets(buffer, 12, stdin) != NULL) {
if (buffer[strlen(buffer) - 1] == '\n') {
buffer[strlen(buffer) - 1] = '\0';
break;
}
}
}
char **check = malloc(sizeof(char**));
long input = strtol(buffer, check, 10);
if (*check[0] == '\0') {
free(check);
*variable = (int) input;
return 1;
}
else {
free(check);
return 0;
}
}
/** /**
* Liberar la memoria al salir * Liberar la memoria al salir
*/ */
@ -177,9 +205,7 @@ int main (int argc, char **argv) {
if (elegir) { if (elegir) {
opt = 0; opt = 0;
fprintf(stdout, "Elegir elemento %lli: ", i + 1); fprintf(stdout, "Elegir elemento %lli: ", i + 1);
while (!fscanf(stdin, "%d", &opt)) { while (!read_buffer(&opt)) {
// Falló, pide de nuevo después de limpiar stdin
while ((opt = getchar()) != '\n' && opt != EOF) { }
fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n"); fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n");
fprintf(stdout, "Elegir elemento %lli: ", i + 1); fprintf(stdout, "Elegir elemento %lli: ", i + 1);
} }
@ -195,22 +221,24 @@ int main (int argc, char **argv) {
} }
if (quick) { if (quick) {
fprintf(stdout, "Quick sort corriendo...\n"); fprintf(stdout, "Quick sort corriendo... ");
fflush(stdout); fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n); memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer(); start_timer();
quick_sort(work_array, n); quick_sort(work_array, n);
stop_timer(); stop_timer();
fprintf(stdout, "done\n");
print_timer(); print_timer();
} }
if (bubble) { if (bubble) {
fprintf(stdout, "Bubble sort corriendo...\n"); fprintf(stdout, "Bubble sort corriendo... ");
fflush(stdout); fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n); memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer(); start_timer();
bubble_sort(work_array, n); bubble_sort(work_array, n);
stop_timer(); stop_timer();
fprintf(stdout, "done\n");
print_timer(); print_timer();
} }
@ -219,12 +247,13 @@ int main (int argc, char **argv) {
} }
if (count) { if (count) {
fprintf(stdout, "Count sort corriendo...\n"); fprintf(stdout, "Count sort corriendo... ");
fflush(stdout); fflush(stdout);
memcpy(work_array, unordered_array, sizeof(int) * n); memcpy(work_array, unordered_array, sizeof(int) * n);
start_timer(); start_timer();
count_sort(work_array, n); count_sort(work_array, n);
stop_timer(); stop_timer();
fprintf(stdout, "done\n");
print_timer(); print_timer();
} }