题目

结构体指针:输出图书信息

思路

本题用结构体存图书信息,并通过结构体指针访问字段输出。

读入数据到 struct Book book,令 p=&book,用 p->title 等形式打印;字符串字段用 %s

解题分析

结构体指针 p->member 等价于 (*p).member。读入时对指针解引用赋值,注意 scanf 字符串要留足空间。

完整程序

#include <stdio.h>

struct Book {
    int id;
    double price;
    char title[64];
};

int main(void)
{
    struct Book b;
    struct Book *p = &b;
    scanf("%d %lf %63s", &p->id, &p->price, p->title);
    printf("id=%d title=%s price=%.2f\n", p->id, p->title, p->price);
    return 0;
}

运行示例

输入:

1 39.9 CPrimer

输出:

id=1 title=CPrimer price=39.90