1

So I have written this simple C program which reads some information in a loop, and then asks the user if the input he gave is correct, but the last input (y\n) is never red from the console.

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

int main(){
    char *name=malloc(sizeof(char)*20),*surname=malloc(sizeof(char)*20),awnser,c;
    int age,tries=1;
    while(1){
        printf("try %d\n",tries++);

        printf("enter name: ");             
        fgets(name,19,stdin);
        strtok(name,"\n");

        printf("enter surname: ");  
        fgets(surname,19,stdin);
        strtok(surname,"\n");

        printf("enter age: ");
        scanf("%d",&age);

        printf("so you are %s %s %d years old? (y/n)\n",name,surname,age);


        awnser=getchar();
        if(awnser=='y'){
            break;
        }
    }
    free(surname);
    free(name);
}

Expected output:

try 1 
enter name: bill 
enter surname: mpris 
enter age: 344 
so you are bill mpris 344 years old? (y/n) 
n 
try 2 
enter name: bill 
enter surname: 
moris enter age: 34 
so you are bill moris 34 years old? (y/n) 
y

Output of the program:

try 1
enter name: bill
enter surname: moris
enter age: 34 
so you are bill moris 34 years old? (y/n)
try 2
enter name:

Does anybody know why that happens? I tried putting fflush(stdin) after every fgets but i still had the same error. I can imagine that it has to do with the buffer and that some character ('\n' probably) is getting read but the getchar

Martian
  • 94
  • 1
  • 9
  • 2
    Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). Change `awnser=getchar();` to `scanf(" %c", &answer);` Note the space before `%c`. – Weather Vane Jun 21 '19 at 16:58
  • 2
    .. however the following `fgets()` in the next loop will now go wrong. Get all inputs with `fgets()` and go from there. `scanf` is tricky enough to use even without mixing it with `fgets` and `getchar`. – Weather Vane Jun 21 '19 at 17:00
  • I see what you mean, thanks a lot!!!!. But for latter on is there somewhere I can learn the hazards of using scanf or any other input function, so I can use them more cautiously?. – Martian Jun 21 '19 at 17:30
  • 1
    There is a great deal in the man pages for `scanf` and its format specifiers. The basic knowledge is that a) most format specifers filter out leading whitespace except `%c` and `%[]`, b) adding a space before the specifier overrides that and cause leading whitespace to be filtered, c) anything that was not read as part of the input remains in the input buffer, such as invalid data and newlines and anything that causes the scan to stop. – Weather Vane Jun 21 '19 at 17:34
  • OK I understand, thanks for the help and the guidance. – Martian Jun 21 '19 at 18:38

0 Answers0