-1

我有一个打印功能:

myprintf("%d ..... other_things_to_print");  
  • 我从许多不同的函数中调用这个 myprintf() 函数。

  • 假设函数 func() 调用 myprintf() 但它没有为“%d”传递任何内容(在上面的 myprintf() 中显示为粗体)。

  • 我不想打印零来代替这个“%d”

我怎样才能避免在这里打印任何东西来代替“%d”?

我试过: '\b', ' ' - 但 myprintf() 正在打印这些字符的等效整数值。

请就这个问题给我一些提示。

谢谢。

此致,

桑迪普·辛格

4

4 回答 4

3

如果您不想%d在没有为其提供参数时打印,则在函数内部使用if()-else结构myprintf()来不输出该位置。这是一个例子:

if( d_variable ) {
    printf("%d ..... other_things_to_print");
} else {
    printf("..... other_things_to_print");
}

这就是if-else允许你做的事情。

于 2012-07-31T15:27:26.580 回答
0

您可以为此目的使用 void 指针,如下所示。

#define ONE_INT        1
#define ONE_INT_ONE_STRING 2


struct print_format
{
    unsigned int type;
    void *data;
}

struct fomat_one_int
{
    int num;
}

struct fomat_one_int_one_Str
{
    int num;
    char *str;
}

.......

void myprintf(struct print_format *format)
{
    unsinged int format_type = 0;

    format_type = format->type;

    switch(format_type)
    {
        case ONE_INT:
        {
            struct format_one_int *f = NULL;
            f = (struct format_one_int *)fomat->data;
            printf("%d some string", f->num);
            break;
        }
        case ONE_INT_ONE_STRING:
        {
            struct fomat_one_int_one_Str *f = NULL;
            f = (struct fomat_one_int_one_Str *)fomat->data;
            printf("%d some string %s", f->num, f->str);
            break;
        }
        ......
    }
}
于 2012-08-05T04:34:10.543 回答
0

而是传递一个指向 int 的指针。

如果指针为 NULL,则不打印 int;如果指针不为 NULL,则打印 int

foo(int *value, const char *txt) {
  if (value && txt) printf("%d %s\n", *value, txt);
  else if (value) printf("%d\n", value);
  else if (txt) printf("%s\n", txt);
  else printf("(no data)\n");
}

你可以用不同的数据调用它

int x = 42; foo(&x, "x");
            foo(NULL, "NULL");
            foo(&x, NULL);
            foo(NULL, NULL);
于 2012-07-31T15:25:53.037 回答
-1

您可以更改 myprintf 以采用多个 args 参数n

void myprintf(int n, int arg1, int arg2, int arg3) {
  if (n == 3) {
    printf("%d %d %d", arg1, arg2, arg3);
  } else if (n == 2) {
        printf("%d %d", arg1, arg2);
  } else if (n == 1) {
        printf("%d" , arg1);
  } else if (n == 0) {
        printf("no");
  }
}

并定义一些宏:

#define myprint0() myprintf(0, -1, -1, -1)
#define myprint1(x) myprintf(1, x, -1, -1)
#define myprint2(x,y) myprintf(2, x, y, -1)
#define myprint3(x,y,z) myprintf(3, x, y, z)
于 2012-07-31T15:22:50.757 回答