我们可以在 C 中的 printf 中对许多格式描述符只使用一个变量吗 [英] Can we use only one variable for many format descriptors in printf in C

查看:33
本文介绍了我们可以在 C 中的 printf 中对许多格式描述符只使用一个变量吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像我在下面写的那样编写代码?

Is is possible to write code like the one I've written in below ?

printf("\n%c%c\n%c",only_one_variable_for_all);
printf("%c%c%c\n",only_one_variable_for_all);

我必须在每种情况下以不同的模式打印你能提供任何其他想法吗?

I have to print in different patterns in each case Can you give any other ideas?

推荐答案

不,这是不可能的.

引用C11,章节§7.21.6.1,fprintf()(适用于*printf()家庭,所有重点都是我的)

Quoting C11, chapter §7.21.6.1, fprintf() (applicale for *printf() family, all emphasis mine)

fprintf 函数将输出写入流指向的流,受控制format 所指向的字符串,指定后续参数如何转换为输出.如果 format 的参数不足,则行为是不明确的.如果 format 用完而参数仍然存在,则多余的参数是评估(一如既往)但被忽略. [...]

The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. [...]

并且,对于包含转换说明符的 format 字符串,

and, for a format string containing conversion specifiers,

format 应该是一个多字节的字符序列,以它的首字母开始和结束转移状态.format 由零个或多个指令组成:普通多字节字符(不是 %),原样复制到输出流;和转换规范,每个规范都会导致获取零个或多个后续参数,如果适用,根据相应的转换说明符转换它们,以及然后将结果写入输出流.**

The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: ordinary multibyte characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments, converting them, if applicable, according to the corresponding conversion specifier, and then writing the result to the output stream.**

所以,归根结底,每个转换规范都需要零个或多个对应"参数,并且一个参数不能对应 format 字符串中的多个转换规范.每个转换规范都需要自己的参数.

So, the bottom line, each conversion specification needs zero or more "corresponding" argument, and one argument, cannot correspond to multiple conversion specification in the format string. Each conversion specification needs their own argument.

解决方案:

如果你想多次打印同一个变量,就像你看到的那样,

In case you want to print the same variable multiple times, like you're shown,

 printf("\n%c%c\n%c",only_one_variable_for_all);

你可以简单地使用一个循环!!

you can simply use a loop!!

 for (int i = 0; i < SOME_SIZE; i++ ) 
 { 
      printf ("%c", only_one_variable ); 

      /* some more logic for line break?*/

 }

这篇关于我们可以在 C 中的 printf 中对许多格式描述符只使用一个变量吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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