[英]How to pass list of arguments in function with variable number of parameters?
我有一个字符串掩码,看起来像这样:
+--\
| \
| \
+---| \
+---| \
+ | \
|\ +---------------------------------+\
| \ | %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| | /
|/ +---------------------------------+/
+ | /
+---| /
+---| /
| /
| /
+--/
我需要printf
它 - printf(string-mask, param1,param2,param3, etc...)
,但参数数量很大(在实际字符串中它大约是40)。 有没有办法避免手动枚举参数?
PS我正在使用纯C.
PSS参数存储在数组中。
迭代数组(字符串),直到找到打印说明符。 然后从值的数组中传递一个参数,然后从前面的位置打印字符串,包括说明符。
这是一个快速而肮脏的解决方案,没有错误检查,假设每个说明符都是%d
并且确实存在param_count
。 字符串也必须是可修改的。
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
以下是输出: https : //ideone.com/zIBsNj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.