0

I have tried to make a function that inputs the type, name and the age of an animal. For the first animal it works just fine but for the second it skips the type. Any idea?

inputAnimalDetails(&ani1);
inputAnimalDetails(&ani2);

void inputAnimalDetails(animal* animal)
{
    char type[LEN] = { 0 };
    char name[LEN] = { 0 };
    int age = 0;
    printf("Enter animal type: ");
    fgets(type, LEN, stdin);
    type[strcspn(type, "\r\n")] = 0;
    strcpy(animal->type, type);
    printf("Enter animal name: ");
    fgets(name, LEN, stdin);
    name[strcspn(name, "\r\n")] = 0;
    strcpy(animal->name, name);
    printf("Enter animal age: ");
    scanf("%d", &age);
    animal->age = age;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • The last thing the first call does is call `scanf`. The first thing the second call does is call `fgets`. `fgets` always has this problem after `scanf`, unfortunately. – Steve Summit May 04 '18 at 21:22

1 Answers1

0

The scanf-statement reads in the integral value, but leaves the new line '\n'-character in the buffer. Hence, in the second round, the first fgets-statement will take up this new line from the buffer and interpret this as an "empty" line, i.e. "skipping" the type then.

To overcome this, either take the newline from the buffer (e.g. fgetch), or - better - use fgets instead of scanf and transform the input into an integral value then.

For example:

char ageStr[LEN] = { 0 };
if (fgets(ageStr, LEN, stdin)) {
  animal->age = strtol(age,NULL,10);
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58