首页 > 解决方案 > 在 C 中打印自定义对象

问题描述

struct在 C中打印 a 的最常见方法是什么?例如,这是我目前正在做的打印Book

typedef struct {
    char* title;
    unsigned int year;
} Book;

void print_book(Book book)
{
    printf("{\n\ttitle: \"%s\",\n\tyear: %d\n}\n", book.title, book.year);
}

int main(int argc, char * argv[])
{

    Book hamlet;
    hamlet.title = "The Tragedy of Hamlet, Prince of Denmark";
    hamlet.year = 1603;
    print_book(hamlet);
    return 0;
}
{
    title: "The Tragedy of Hamlet, Prince of Denmark",
    year: 1603
}

编写自定义独立函数(例如print_book)是最常见的方法吗?或者有没有办法将“打印”方法更紧密地绑定到结构/类型定义?

标签: cstruct

解决方案


推荐阅读