Ignorante

26 Octubre 2007

Leer un entero de teclado en C

Archivado en: Programación — ignorante @ 23:54
Tags: ,

Sin usar scanf, porque no sirve para leer de teclado.

#include<stdlib.h>
#include<stdio.h>

#define MAX_DIGITS 9
#define BASE 10

static int* BUFFER = NULL;

int* readInt()
{
int i = 0,
j = 0,
base = 1,
factor = 1,
*result,
ch = getchar();
if(BUFFER == NULL){
BUFFER = malloc(MAX_DIGITS * sizeof(int));
}
if(ch == 45){
factor = -1;
ch = getchar();
}
while(i < MAX_DIGITS && ch != 10 && ch != -1 && 48 <= ch && ch <= 57){
BUFFER[i++] = ch;
ch = getchar();
}

if(i == 0 || (ch != 10 && ch != -1)){
while(ch != 10 && ch != -1){
/* consumo lo que haya en el buffer para vaciarlo.*/
ch = getchar();
}
return NULL;
}
/* transformo el string en un entero según la base.*/
result = (int*) malloc(sizeof(int));
*result = 0;
/* De atrás para adelante, multiplicando por la base y sumando.*/
for(j = i – 1; j >= 0; j = j-1){
*result += ( BUFFER[j] – 48 ) * base;
base *= BASE;
}
/* aplico el signo*/
*result *= factor;
return result;
}

3 comentarios »

  1. no funciona!!

    Comment por mm..... — 22 Noviembre 2007 @ 16:56

  2. si funciona….!!

    Comment por mm..... — 22 Noviembre 2007 @ 17:07

  3. [...] Hace un tiempo publiqué cómo leer un entero de teclado. Ahora le corregí un bug y le mejoré el uso de [...]

    Pingback por La función scanf y la lectura de la entrada de teclado « Ignorante — 17 Abril 2008 @ 17:51


Canal RSS de los comentarios de la entrada. URI para TrackBack.

Deja un comentario

Blog de WordPress.com.