I am trying to make a C console application collect (via keyboard) special Spanish characters like accents, 'ñ', etc in a scanf
or in gets
.
I have managed to display these characters correctly (stored in a variable or, directly, from the printf
) thanks to the locale.h
. I show an example:
#include <stdio.h>
// Añade paquete de idiomas
#include <locale.h>
int main(void)
{
// Declaración de variables
char cadena[254];
// Establecer el idioma a español
setlocale(LC_ALL, "spanish");
// Mostrar correctamente los caracteres especiales del español
printf("¡Éxito!. Se muestran los caracteres especiales del español.");
printf("Introduce un string con caracteres especiales: ");
gets(cadena);
printf("El string con caracteres especiales que has introducido es: %s", cadena);
return 0;
}
but I still couldn't get them to be picked up correctly with the functions mentioned above.
Does anyone know how to do it?
Thank you
EDIT 1:
Doing tests I have observed that:
setlocale(LC_ALL, "spanish");
It shows the Spanish characters correctly, but it doesn't pick them up from the keyboard.setlocale(LC_ALL, "es_ES");
It collects the Spanish characters correctly from the keyboard, but it does not display them correctly.
I have found a solution to the problem. Apparently this problem only appears in Windows and its command console.
It consists of changing the encoding of both input and output of the windows console with the commands
SetConsoleCP()
andSetConsoleOutputCP()
(for this it is also necessary to include the headerwindows.h
). With that the problem is solved. I hope it helps other people who have the same problem as me.All the best.