结构出错了

时间:2016-03-09 08:59:20

标签: c

代码是关于某些形状的,我想让它输入有关形状的所有细节,然后打印它们。但由于某种原因,我无法输入结构的第二个名称。请帮忙吗?

#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);
}

1 个答案:

答案 0 :(得分:1)

fgets(name, LENGTH, stdin);替换为:

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

您正在从最后一个结构中读取未使用的'\n'(在您读取数字后左侧。

或者,如果您的名称不包含空格字符,您还可以使用以下内容:

scanf(" %s", name);
/*     ^  space   */