How to Solve
This problem is caused by the operation of scanf
itself. To resolve this, simply modify this snippet of code:
scanf("%d", &dados->mm_prec);
printf("Qual nome?");
fgets(dados->nome,200,stdin); /*problema, está ficando algum "lixo de memória" que não deixa meu fgets capturar o nome*/
To:
scanf("%d", &dados->mm_prec);
fflush(stdin);
printf("Qual nome?");
fgets(dados->nome,200,stdin); /*problema, está ficando algum "lixo de memória" que não deixa meu fgets capturar o nome*/
The fflush
function is used to clear a data stream , in this case the stdin
stream, which is the stream from which you want to read the data needed for the program to work. When using fflush
before fgets
, you will be cleaning the garbage created by scanf
.
What causes the problem?
The problem is in the scanf
function itself. Analyze, for example, the following call to the scanf function:
scanf("%d", &variavel);
Exactly what you asked for: It reads integers : Numbers that you type in stdin. So when you type:
450
And press enter, what was the string created in this process? If scanf
only reads the numbers that were typed by the user, it gets the following stdin characters:
4
, 5
and 0
But ignores the following character, which is not a number:
\n
That's right! When you press the enter key for scanf to read, scanf ignores the enter entered in stdin. Therefore, stdin goes from:
450\n
To:
\n
So when fgets
is to read the string that the user supposedly should have typed, it already finds the newline character \n
in stdin
, which was left behind by scanf
. This way, fgets
is basically "ignored" by your code. This is why you should use fflush
after scanf: To clear those remnants left by scanf
.