0

I am having a problem with a for loop. When I go through the second iteration, the program does not wait for user input. Any help gratefully accepted.

#include <stdio.h>
#include "dogInfo.h"


main()
{
    struct dogInfo dog[3];  //Array of three structure variable
    int ctr;

    //Get information about dog from the user
    printf("You will be asked to describe 3 dogs\n");
    for (ctr = 0; ctr < 3; ctr ++)
    {
       printf("What type (breed) of dog would you like to describe for dog #%d?\n", (ctr +1));
       gets(dog[ctr].type);
       puts("What colour is the dog? ");
       gets(dog[ctr].colour);
       puts("How many legs does the dog have? ");
       scanf(" %d", &dog[ctr].legNum);
       puts("How long is the snout of the dog in centimetres? ");
       scanf(" %.2f", &dog[ctr].snoutLen);
       getchar(); //clears last new line for the next loop
    }

The header file is as below

 struct dogInfo
{
    char type[25];
    char colour[25];
    int legNum;
    float snoutLen;
};

1 Answers1

0

Your problem is that gets is not behaving in the way you want it to. You should not be using gets anyway because it is dangerous and can cause overflows. But fortunately scanf can easily read strings and also allows to specify a format (in this case %24s because you want to read up to 24 chars, because the last char is reserved for the Null-terminator.

The code works like this:

#include <stdio.h>
struct dogInfo
{
    char type[25];
    char colour[25];
    int legNum;
    float snoutLen;
};

int main()
{
    struct dogInfo dog[3];  //Array of three structure variable
    int ctr;

    //Get information about dog from the user
    printf("You will be asked to describe 3 dogs\n");
    for (ctr = 0; ctr < 3; ctr ++)
    {
       printf("What type (breed) of dog would you like to describe for dog #%d?\n", (ctr +1));
       scanf("%24s", dog[ctr].type);
       puts("What colour is the dog? ");
       scanf("%24s", dog[ctr].colour);
       puts("How many legs does the dog have? ");
       scanf(" %d", &dog[ctr].legNum);
       puts("How long is the snout of the dog in centimetres? ");
       scanf(" %.2f", &dog[ctr].snoutLen);
       getchar(); //clears last new line for the next loop
    }
}
Jina Jita
  • 136
  • 1
  • 3
  • Thanks, but can you tell me why the first iteration is OK, but for the second iteration C won't wait for user input? Thanks – stephen Ong Feb 11 '20 at 23:10