0

The code is about some shapes, I want it to get input all the details about the shapes and than prints them. but from some reason I can't input the second name of the struct. help please?

#include <stdio.h>
#define LENGTH 30   
struct shape
{
    char name[LENGTH];
    int edge;
    int special;
};
void addingshape(struct shape shp1[],int i);
int main(void)
{
    struct shape arrshape[2];
    printf("\nLets enter your first shape:\n");
    addingshape(arrshape,0);
    printf("\nLets enter your seconed shape");
    addingshape(arrshape,1);
    system("PAUSE");
    return 0;
}
void addingshape(struct shape shp1[],int i)
{
    int edge, special;
    char name[LENGTH] = { 0 };
    printf("Please enter details of some shape\n");
    printf("Enter name of the shape\n");
    fgets(name, LENGTH, stdin);
    name[strcspn(name, "\n")] = 0;
    strcpy(shp1[i].name, name);
    printf("Please enter number of edge's\n");
    scanf("%d", &edge);
    shp1[i].edge = edge;
    printf("Now enter 1 if the shape is special, and 0 if the shape is not special\n");
    do
    {
        scanf("%d", &special);
        if (special != 1 && special != 0)
        {
            printf("not good choice, please try again\n");
        }
    } while (special != 1 && special != 0);
    shp1[i].special = special;
    printf("The name of the shape: %s\nNumber of edge's is: %d\nIf the shape is special: %d\n", shp1[i].name, shp1[i].edge, shp1[i].special);
}
DR J
  • 73
  • 7

1 Answers1

1

Replace fgets(name, LENGTH, stdin); with:

do { fgets(name, LENGTH, stdin); } while(name[0] == '\0' || name[0] == '\n');

You are reading unused '\n' from last struct (Left after you read the number.

Alternatively if you name doesn't contain space character, you can also use the following:

scanf(" %s", name);
/*     ^  space   */
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100