gpt4 book ai didi

c - scanf 没有在结构中存储正确的信息

转载 作者:太空宇宙 更新时间:2023-11-04 04:56:48 24 4
gpt4 key购买 nike

scanf 有问题。 scanf 没有在结构中存储正确的信息。部分代码为:

if( figure->pro.p_category == 'C' || figure->pro.p_category == 'c' ){
printf("Enter data line> ");
result += scanf("%s %d%c %d %d %d%c", (figure->pro.name), &temp,\
&figure->pro.money, &figure->exp.month, &figure->exp.year,\
&figure->ais.aisle_num, &figure->ais.aisle_side);
if ( figure->pro.money == 'C')
figure->pro.cents = temp;
else if( figure->pro.money == 'D')
figure->pro.dollars = temp;
}

figure->pro.namefigure->exp.month 存储不同的值。

我的结构是:

typedef struct {
char name[20];
char p_category,
sub_p_category,
money;
int cents,
dollars;
}product_t;

typedef struct {
int aisle_num;
char aisle_side;
}aisle_t;

typedef struct {
int day,
month,
year;
}experiment_t;

typedef struct {
int day,
month,
year;
}packaging_t;

typedef union {
product_t pro;
experiment_t exp;
packaging_t pack;
aisle_t ais;
}figure_t;

例如;

input> corn 89C 11 2010 11B

这段输出函数的代码:

printf("The %s costs %d cents, expires in ",my_figure.pro.name, my_figure.pro.cents);

print_exp_month(my_figure);
printf("of %d, and is displayed in %d%c", my_figure.exp.year, my_figure.ais.aisle_num,\
my_figure.ais.aisle_side);

它的输出:

The

costs 89 Dollar, expires in of 2000, and is displayed in 12B

正确的输出:

The corn costs 89 cents, expires in November of 2000, and is displayed in 12B

最佳答案

如果您将数据存储在 union 中

typedef union {
product_t pro;
experiment_t exp;
packaging_t pack;
aisle_t ais;
} figure_t;

每次只存储一组数据。例如,当您读入 figure->pro.moneyfigure->exp.month 时,数据将存储在同一位置并相互覆盖。

所以当您尝试打印它时,它已经不存在了!

关于c - scanf 没有在结构中存储正确的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6321574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com