How could I read a character string and store it in a variable?
To read a value from the keyboard you can use scanf
. To this function you must indicate the format of the data you want to read and the address of the variable in which you want to read them, let's see it in an example:
int numero = 0;
scanf("%d", &numero);
The "%d"
indicates that you intend to read a number, if you want to read a string of characters you should use "%s"
:
char cadena_de_caracteres[100];
scanf("%s", cadena_de_caracteres);
Here we do not use the operator address-of ( the et &
) because the name of the fix equivalent to the address of the first element of it. Keep in mind that reading "%s"
adds the end character of control : the null character .
The variable must not have a fixed size.
If it is not a fixed size: it is variable size. To do this you must first find out the size of the string you want to read and then read the string:
int longitud_de_la_cadena = 0;
printf("Longitud de la cadena: ");
scanf("%d", &longitud_de_la_cadena);
char *cadena = (char *)malloc(longitud_de_la_cadena + 1);
printf("Cadena: ");
scanf("%s", cadena);
printf("\"%s\" es la cadena de %d caracteres introducida.\n", cadena, longitud_de_la_cadena);
The previous code by entering the values 6
and patata
shows:
Longitud de la cadena: 6
Cadena: patata
"patata" es la cadena de 6 caracteres introducida.
Here we use malloc
to accommodate the size we need for our variable length string, not we must forget to release the requested memory before finishing the program using the function free
:
free(cadena);