【问题标题】:scanf doesn't store proper information in structurescanf 没有在结构中存储正确的信息
【发布时间】:2011-06-12 11:03:14
【问题描述】:

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.name 和 figure->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);

它的输出:

售价 89 美元,2000 年到期,显示为 12B

正确的输出:

玉米价格为 89 美分,2000 年 11 月到期,显示在 12B 中

【问题讨论】:

  • 欢迎来到stackoverflow!如果您能告诉我们究竟哪些信息“未正确存储”,以及究竟什么构成“未正确存储”,将对我们有很大帮助。此外,您可能希望简化您的问题。如果您只是scanf("%s", (figure->pro.name));,问题是否仍然存在?
  • "ctype.h", tolower()/toupper().
  • 在 C 语言中,你不需要在换行行的末尾加上 '\'。你只需要它们用于跨越多行的预处理器指令。
  • 我的输入是corn.But,它只存储空白
  • 不要对结构进行 typedef。他们已经有了类型。你所做的只是让你的代码变得不那么简单和直接。

标签: c struct scanf


【解决方案1】:

如果您将数据存储在联合中

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2021-04-26
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多