I'm trying to use gets to store a name/little phrase
It was supposed to hold 39 chars, but after I enter the first char it returns to the previous cycle. ( I have a Do While showing content on the main)
Why doesn't it work as supposed?
char nome[40];
printf("\nNome do Equipamento: ");
gets(nome);
strcpy(eq[n].nomeEquipamento, nome);
In the link you have provided, there is a scanf
call before gets
printf("\nCodigo do Equipamento: ");
scanf("%d",&codigo);
eq[n].codDipositivo=codigo;
printf("\nNome do Equipamento: ");
gets(nome);
The scanf
call leaves behind \n
character after pressing Enter key. This \n
character is read by gets
and that's why you are facing this problem.
To consume this \n
, use a getchar
starement just after the scanf
;
printf("\nCodigo do Equipamento: ");
scanf("%d",&codigo);
getchar(); // To comsume '\n'
eq[n].codDipositivo=codigo;
printf("\nNome do Equipamento: ");
gets(nome);
Now about gets
; Happy to sat that the evil gets
is a history now. Use fgets
instead.
And also do not use strcpy
, instead you can use strncpy
(before using it, read the prrovided link carefully).