【问题标题】:Printf with conditional format [duplicate]具有条件格式的 Printf [重复]
【发布时间】:2021-02-09 13:27:42
【问题描述】:

我想打印基于mode 值的变量数。这是一个例子:

char format[64] = {}
int mode_1, mode_2, mode_3;
int a,b,c,d,e,f;

...
// Get mode value here ....
...

// Build the format first
sprintf(format, "%s-%s-%s\n", mode_1 == 0 ? "a=%d,b=%d" : "a=%d",
                              mode_2 == 0 ? "c=%d,d=%d" : "c=%d",
                              mode_3 == 0 ? "e=%d,f=%d" : "e=%d");

// Print value here
printf(format, mode_1 == 0 ? (a,b) : a,
               mode_2 == 0 ? (c,d) : c,
               mode_3 == 0 ? (e,f) : f);

当我尝试一个简单的例子时,当模式值为零时打印的值似乎不正确。我在这里做错了什么?

【问题讨论】:

  • When I tried a simple example 请不要发布截图。请将文本作为文本发布。
  • ?: 是一个运算符,因此它有 1 个结果值。在这两种情况下,您不能使用它来评估多个值甚至不同数量的结果。

标签: c format printf conditional-operator comma-operator


【解决方案1】:

这个表达式

(a, b)

是带有逗号运算符的表达式。表达式的结果是最后一个操作数的值。

就是这个电话

printf(format, mode == 0 ? (a,b): a);

其实就相当于调用

printf(format, mode == 0 ? b: a);

你可以写

mode == 0 ? printf(format, a, b ) : printf( format, a );

如果 printf 的调用形式取决于整数变量 mode,那么您可以使用例如 switch 语句或 if-else 语句。

【讨论】:

  • 但实际上我有不止 1 个 mode 变量(在我的示例代码中,不在屏幕截图中)。那么我应该怎么做才能让它变得简单呢?
  • @Tino 您可以使用 if-else 语句或 switch 语句。
猜你喜欢
  • 1970-01-01
  • 2020-09-26
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
相关资源
最近更新 更多