[英]How to pass list of arguments in function with variable number of parameters?
I have a string-mask that looks something like this: 我有一个字符串掩码,看起来像这样:
+--\
| \
| \
+---| \
+---| \
+ | \
|\ +---------------------------------+\
| \ | %d| %d| %d| %d| %d| | \
| \| %d| %d| %d| %d| %d| | |\
| | %d| %d| %d| %d| %d| | | \
|---| | | \
|---| | | /
| | %d| %d| %d| %d| %d| | | /
| /| %d| %d| %d| %d| %d| | |/
| / | %d| %d| %d| %d| %d| | /
|/ +---------------------------------+/
+ | /
+---| /
+---| /
| /
| /
+--/
I need to printf
it - printf(string-mask, param1,param2,param3, etc...)
, but number of parameters is a huge (in real string it is about 40). 我需要
printf
它 - printf(string-mask, param1,param2,param3, etc...)
,但参数数量很大(在实际字符串中它大约是40)。 Is there way to avoiding manual enumeration of parameters? 有没有办法避免手动枚举参数?
PS I'm using pure C. PS我正在使用纯C.
PSS params are storing in array. PSS参数存储在数组中。
Iterate the array (the string), until you hit a print specifier. 迭代数组(字符串),直到找到打印说明符。 Then print the string from where you previously left of, to, including, the specifier, while passing a single argument from the array of values.
然后从值的数组中传递一个参数,然后从前面的位置打印字符串,包括说明符。
This is a quick and dirty solution without error checking that assumes every specifier is exactly %d
and there are exactly param_count
of them. 这是一个快速而肮脏的解决方案,没有错误检查,假设每个说明符都是
%d
并且确实存在param_count
。 Also the string must be modifiable. 字符串也必须是可修改的。
const size_t param_count = 30;
char* first = string;
char* last = string;
for( size_t i = 0 ; i < param_count ; i++ )
{
last = strchr( last , '%' ); //find the specifier
last += 2 ; //skip the specifier
const char temp = *last;
*last = '\0'; //terminate the 'sub-string'
printf( first , param[i] );
*last = temp; //restore the 'string'
first = last;
}
printf( first ); //print the remaining string
Here is the output: https://ideone.com/zIBsNj 以下是输出: https : //ideone.com/zIBsNj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.