-1

The program won't compile fgets in the teste1 function. Or at least it isn't working properly, it won't let me type the string, the program will end right after it prints "Nome do cliente".

If I disable the other scanf's in the function, it will run without any issue.

How do I make fgets to work?

#include <stdio.h>
void teste1(){
    char teste[50];
    printf("Nome do cliente\n");
    fgets(teste,50,stdin);
}

void teste2(){
    teste1();
}

void teste3(){

        int opc1,opc2;
        printf("\nSeleccione a área desejada\n1- Clientes\n2- Concessionários\n3- Carros de demonstração\n");
        scanf("%d",&opc1);

        printf("\nSeleccione a área desejada\n1- Inserir\n2- Alterar\n3- Remover\n4- Consultar\n");    
        scanf("%d",&opc2);

    teste2();
}

int main()
{
    teste3();
}
xickoh
  • 304
  • 3
  • 10

1 Answers1

1

The Enter key you pressed for the last scanf input will be left in the input buffer as a newline. The fgets function will read this newline and think it is finished.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • How do I fix that? – xickoh Jan 24 '17 at 15:03
  • 3
    @xickoh: Several choices. One is to use `fgets()` to read lines and then `sscanf()` to analyze them — that's probably the best. An alternative is to gobble the characters up to newline (or EOF) after the `scanf()`, using code like: `int c; while ((c = getchar()) != EOF && c != '\n') ;`. Note that as it stands (in the question), the user could type `3 4 Frederick Handel` all on one line and that would satisfy all your input code. With `fgets()` plus `sscanf()`, you regain control over what the user enters (or what you do with what the user enters). – Jonathan Leffler Jan 24 '17 at 15:05
  • @Jonathan Leffler does fgets() read integers? I only intend to read a single integer in that scanf – xickoh Jan 24 '17 at 15:07
  • @xickoh: No, `fgets()` reads strings; that's why you use `sscanf()` afterwards to analyze the string and convert it to an integer, if that's possible. You also have the data available to present in an error message: `You typed 'Albuquerque' but that cannot be converted to an integer`, for example. – Jonathan Leffler Jan 24 '17 at 15:09
  • @Jonathan Leffler can you please provide me an example of a working function doing that? I'm struggling with this since yesterday and I need to finish this project by the end of the day. – xickoh Jan 24 '17 at 15:13
  • 1
    The quickest fix is to add the while loop I showed after the second `scanf()` in the `teste3()` function. You want a line of input; you make sure you're at the start of a line. You don't actually do anything with the name you read; you should at least print it. You should also be checking that the input operations worked: `if (scanf("%d", &opc1) != 1) { …handle error… }` and `if (fgets(teste, sizeof(teste), stdin) == 0) { …handle error… }`. – Jonathan Leffler Jan 24 '17 at 15:18
  • That worked, I'm very appreciated. – xickoh Jan 24 '17 at 15:23