-What I wanted to do, I could not implement it, is that when asking for a name and a surname to the user a priori we DO NOT KNOW what will be the stdin length that the user types. In the malloc line I put 10 to put as I could have put 20 but in fact I do not know how much will occupy the name and surname that I enter the user keyboard I do not know how to implement it in such a way that when you type a name and a surname calculate the length and then and reserve memory for that length to part also to reserve the memory just and necessary for what I type the user and not walk blind assuming that you enter a name and last name of 10,20,30 etc bytes
-As I did not go out, I did this that does not look like anything I wanted to do in the beginning and that even above I can not make it work the way I want to do it. I hope you have explained me clearly and thank you
First doubt, because the code does not work as it should? fault of the fgets?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *nombre,*nombre2;
nombre=malloc(10*sizeof(char)); //reservo 10 bytes
printf("Introduce tu nombre y apellido: ");
fgets(nombre,9,stdin); //agrega NULL y \n si se ingresan menos caracteres
if (nombre[strlen(nombre)-1] == '\n'){
nombre[strlen(nombre)-1] = 'while(1):
cadena=str(input("Introduce lo que quieras o exit para salir: "))
if(cadena=="exit"):
break
print(cadena)
';
}
printf("%s\n",nombre);
long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena
printf("%li\n",longitud);
if(longitud>8){
nombre2=realloc(nombre,15*sizeof(char)); //reasigno 5 bytes
printf("%s\n",nombre);
free(nombre2);
}
free(nombre);
return 0;
}
Second doubt, would it be possible to implement it?
Regarding the idea if someone knows python the code that I want to implement in c would be something like this in python:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *nombre,*nombre2;
nombre=malloc(10*sizeof(char)); //reservo 10 bytes
printf("Introduce tu nombre y apellido: ");
fgets(nombre,9,stdin); //agrega NULL y \n si se ingresan menos caracteres
if (nombre[strlen(nombre)-1] == '\n'){
nombre[strlen(nombre)-1] = 'while(1):
cadena=str(input("Introduce lo que quieras o exit para salir: "))
if(cadena=="exit"):
break
print(cadena)
';
}
printf("%s\n",nombre);
long int longitud=(strlen(nombre)+1); //strlen no cuenta el NULL de final de cadena
printf("%li\n",longitud);
if(longitud>8){
nombre2=realloc(nombre,15*sizeof(char)); //reasigno 5 bytes
printf("%s\n",nombre);
free(nombre2);
}
free(nombre);
return 0;
}