当使用C一行打印结构? [英] Printing the structure using a single line in C?

查看:129
本文介绍了当使用C一行打印结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有用C任何可能的方式(通过使用任何功能或任何此类),因此我们可以使用一行打印在不同的数据类型的结构的内容?
说了例如:

Is there any possible way in C (by using any function or any such kind) so that we can print the contents in a structure of different datatypes using a single line? Say for eg:

typedef struct ABC{
   int a;
   char b;
   long c;
}ABC1;

要打印此,我们需要这样写:
的printf(%D%S%LD,ABC1.a,ABC1.b,ABC1.c)

To print this we need to write: printf("%d %s %ld",ABC1.a,ABC1.b,ABC1.c)

任何其他方法,这样我就可以像打印
的printf(????,???? ABC1) ??

Any other method so that i can print like printf("????",????ABC1)??

推荐答案

的Glibc允许你建立自己的格式说明的printf 和家人,让您打印的UDT,这本来没有可能的,通过一些扩展。

Glibc allows you to establish your own format specifiers for printf and family to let you print UDTs, which would not otherwise be possible, through some extensions.

#include <stdio.h>
#include <printf.h> /* For PA_POINTER */

struct MyStruct
{
    int a;
    double b;
};

struct print_info;
int handler(FILE *stream, const struct print_info *i, 
        const void* const *args)
{
    const struct MyStruct *ptr = *( (const struct MyStruct**) (*args) );
    int rc = fprintf(stream, "a: %d, b: %f\n", ptr->a, ptr->b);

    return rc;
}

int print_arginfo (const struct printf_info *info, size_t n,
                      int *argtypes)
{
  if (n > 0)
    argtypes[0] = PA_POINTER;
  return 1;
}

int main(void)
{
    struct MyStruct s = {55, -3.14};
    /* We're gonna use the M specifier */
    int spec = 'M';
    int rc = register_printf_function(spec, handler, print_arginfo);

    if (rc != 0)
        return 1;

    printf("%M", &s);

};

您可能会发现的文档这里

这篇关于当使用C一行打印结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆