PROBLEM WITH FGETS IN C

Asked

Viewed 2,257 times

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;
}

1 answer

0

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.

  • 1

    Thank you very much!!!

  • I’m glad I helped! If you have any questions, just ask

Browser other questions tagged

You are not signed in. Login or sign up in order to post.