PROBLEM WITH FGETS in C [duplicate]

0
#include <stdio.h>
#include <stdlib.h>

/*definir operador lógico para chuva (1 para TRUE e 0 para FALSE) */

#define TRUE (1==1)
#define FALSE (!TRUE)

struct eventos_atm_st {
float temp;
float press;
int chuva;
int mm_prec;
char nome[200];
};

typedef struct eventos_atm_st eventos;

void ler_estrutura(eventos *dados){
printf("Qual temperatura?\n");
scanf("%f", &dados->temp);
printf("Qual pressao?\n");
scanf("%f", &dados->press);
printf("choveu?\n");
scanf("%d", &dados->chuva); /*definir 1 para true e 0 para false */
printf("Qual mm_prec?\n");
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*/



}



int main(){

eventos node[3];
int i;

for(i=0;i<3;i++){
ler_estrutura(&node[i]);
}


return 0;
}
    
asked by anonymous 13.05.2017 / 04:20

1 answer

0

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 .

    
13.05.2017 / 21:09