How do I use fgets instead of gets?

Asked

Viewed 3,668 times

0

before "talking" about my problem, first look at my code and ignore the accent errors in the console if you are going to run.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main(){
  char nome[41];
  printf("Texto: ");
  fgets(nome, 40, stdin);
  if (strcmp(nome, "0") == 0) {
    printf("Sim. fgets está funcionando.\n");
  } else {
    printf("Não. fgets não está funcionado.\n");
  }
  printf("Texto: ");
  gets(nome);
  if (strcmp(nome, "0") == 0){
    printf("Sim. gets está funcionando.\n");
  } else {
    printf("Não. gets não está funcionando.\n");
  }
}

inserir a descrição da imagem aqui

When I type "0" by command fgets, IF does not find "0", BUT when I type "0" by gets IF finds the "0".

I want to avoid the gets, as many sites/books recommend not to use this command as it is dangerous and gives buffer error. (so far, I have not had problems related to buffer) but infrequent the fgets is not working as I wanted, only the gets is working on my codes, but I want to avoid.

Does anyone know how to do the fgets have the character detected by the IF

1 answer

1


The fgets function puts ' n' at the end of the read string. So, in this case, the "name" content will be "0 n", not just "0".

http://linux.die.net/man/3/fgets

  • Thanks for your help, thanks to you the same codes will get better and thanks for the site that ported.

Browser other questions tagged

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