通过循环(字符* C,...) [英] loop through (char *c, ...)
本文介绍了通过循环(字符* C,...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新的C,和我通过常规的参数需要循环:
I'm new to C, and I need to loop through arguments of a routine:
void doSmth(char *c, ...) { //how to print all the elements here? }
由于我来自爪哇,这是一个相当新的给我,我不知道该怎么做这在C?
Since I come from Java, this is quite new to me, and I have no idea how to do this in C?
在此先感谢
推荐答案
由于您的函数的声明是这样的:
Because your function declaration is like:
无效doSmth(字符* C,...);
您需要什么叫可变数量的参数功能,可以读取: 9.9。可变的参数个数一个很好的和作文教程
What you needs is called variable number of argument functions, you can read from : 9.9. Variable numbers of arguments a good and essay tutorial
例子code。与功能doSmth()的第4步,阅读评论的:
Example code with function doSmth() its 4 steps, read comments:
//Step1: Need necessary header file
#include <stdarg.h>
void doSmth( char* c, ...){
va_list ap; // vlist variable
int n; // number
int i;
float f;
//print fix numbers of arguments
printf(" C: %s", c);
//Step2: To initialize `ap` using right-most argument that is `c`
va_start(ap, c);
//Step3: Now access vlist `ap` elements using va_arg()
n = va_arg(ap, int); //first value in my list gives number of ele in list
while(n--){
i = va_arg(ap, int);
f = (float)va_arg(ap, double); //notice type, and typecast
printf("\n %d %f \n", i, f);
}
//Step4: Now work done, we should reset pointer to NULL
va_end(ap);
}
int main(){
printf("call for 2");
doSmth("C-string", 2, 3, 6.7f, 5, 5.5f);
// ^ this is `n` like count in variable list
printf("\ncall for 3");
doSmth("CC-string", 3, -12, -12.7f,-14, -14.4f, -67, -0.67f);
// ^ this is `n` like count in variable list
return 1;
}
运行它,如:
:~$ ./a.out
call for 2 C: C-string
3 6.700000
5 5.500000
call for 3 C: CC-string
-12 -12.700000
-14 -14.400000
-67 -0.670000
<子>在C语言中的东西其实是参数后跟可变的参数个数固定数量
这篇关于通过循环(字符* C,...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文