Skip to content

Instantly share code, notes, and snippets.

@MrDave1999
Last active July 14, 2020 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrDave1999/09b90de748b9da01490a724aef3df98d to your computer and use it in GitHub Desktop.
Save MrDave1999/09b90de748b9da01490a724aef3df98d to your computer and use it in GitHub Desktop.
Función readLine() en C
#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