Last active
July 14, 2020 13:56
-
-
Save MrDave1999/09b90de748b9da01490a724aef3df98d to your computer and use it in GitHub Desktop.
Función readLine() en C
This file contains 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> | |
#include <string.h> | |
char* readLine(void); | |
int main(void) | |
{ | |
char* buf; | |
printf("Ingrese un nombre:\n"); | |
buf = readLine(); | |
if(buf == NULL) | |
{ | |
printf("No se puso asignar memoria dinamica!"); | |
return 1; | |
} | |
printf("String: %s, length: %d\n", buf, strlen(buf)); | |
free(buf); | |
return 0; | |
} | |
char* readLine() | |
{ | |
int i = 0; | |
int ch; | |
char* aux; | |
char* buf; | |
buf = malloc(sizeof(char)); | |
if(buf == NULL) | |
return NULL; | |
while((ch = getchar()) != '\n') | |
{ | |
buf[i++] = ch; | |
aux = buf; | |
buf = realloc(buf, (i+1)* sizeof(char)); | |
if(buf == NULL) | |
{ | |
free(aux); | |
return NULL; | |
} | |
} | |
buf[i] = '\0'; | |
return buf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment