代码可以运行,但有一些小错误,我不知道它在哪里?

时间:2014-11-16 06:57:55

标签: c random input structure

以下代码可以在编译器中正确运行但是有一些小错误我无法识别出来。它只能输入第一个汽车细节但是当它到达第二个记录时它跳转到第二个输入语句而不是第一个输入语句。请指出校正的位置并感谢你所做的一切。

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

struct auto_t
{
    char make[20];
    char model[20];
    int oRead;
    int manufDate;
    int purchDate;
    float cpct;
    float f_level;
};

int main(int argc, char** argv)
{
    struct auto_t automobile[2];
    int i;
    for(i=0; i<2; i++)
    {
        printf("component:");
        gets(automobile[i].make);
        printf("model:");
        gets(automobile[i].model);
        printf("Odoer reading:");
        scanf_s("%d", &automobile[i].oRead);
        printf("manufacturing date(ddmmyyyy):");
        scanf_s("%d", &automobile[i].manufDate);
        printf("purchasing date(ddmmyyyy):");
        scanf_s("%d", &automobile[i].purchDate);
        printf("capacity:");
        scanf_s("%f", &automobile[i].cpct);
        printf("fuel level:");
        scanf_s("%f", &automobile[i].f_level);
        printf("\n");
    }
    printf("\nName\tModel\tOReaad\tManufDate\tPurchDate\tCpct\tFuel\n");
    for(i=0; i<2; i++)
    {
        printf("%s\t%s\t%d\t%d\t%d\t%.f\t%.f\n", automobile[i].make, automobile[i].model, automobile[i].oRead, automobile[i].manufDate, automobile[i].purchDate, automobile[i].cpct, automobile[i].f_level);
    }
    system("pause");
}

1 个答案:

答案 0 :(得分:0)

Never use gets() as it is dangerous。请改用fgets()。所以改变

printf("component:");
gets(automobile[i].make);
printf("model:");
gets(automobile[i].model);

printf("component:");
fgets(automobile[i].make,20,stdin);
printf("model:");
fgets(automobile[i].model,20,stdin);

printf("component:");
fgets(automobile[i].make,sizeof(automobile[i].make),stdin);
printf("model:");
fgets(automobile[i].model,sizeof(automobile[i].model),stdin);