How To Solve
This problem is caused by the very functioning of scanf
. To solve it, just modify this code snippet:
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*/
for:
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 function fflush
serves to clear a data flow, in case the flow stdin
, 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 lies in the function itself scanf
. Analyze, for example, the following call to the scanf function:
scanf("%d", &variavel);
Makes exactly what you asked for: She reads whole: Numbers you type in stdin. So when you type:
450
And hit enter, what was the string created in this process? Well, if scanf
only reads the numbers that were typed by the user, it obtains the following stdin characters:
4
, 5
and 0
But she ignores the following character, which is not a number:
\n
That’s right! When you press the button enter for scanf to perform its reading, scanf ignores the entered enter in stdin. Therefore, stdin passes from:
450\n
To:
\n
So when fgets
for reading the string that the user supposedly should have typed, it already finds the new line character \n
in stdin
, who was left behind by scanf
. In this way, fgets
is basically "ignored" by your code. That’s why you should use fflush
after scanf: To clean up these remnants left by scanf
.
First, don’t mix
fgets
withscanf
. Afterward, see here how to solve this.– Victor Stafusa
Ah, and just so we’re clear. I’m not the one who negatively challenged you. On the contrary, I consider your doubt valid.
– Victor Stafusa