用变量参数count调用C函数



如何重写下面的代码块?我需要通过函数token()提取一些参数,然后用这些参数调用printf。参数数目未知

char *S[32]; int i=0;
while (t) {
    char *s=token(&t, lineno, 0);
    assert(i<sizeof(S)/sizeof(S[0]));
    S[i++]=s;
}
printf(f, S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[8], S[9],
     S[10], S[11], S[12], S[13], S[14], S[15], S[16], S[17], S[18], S[19],
     S[20], S[21], S[22], S[23], S[24], S[25], S[26], S[27], S[28], S[29],
     S[30], S[31]);

我认为你应该使用vprintf:Vprintf参考cplusplus.com

array[] = { aPointer,aPointer,...,NULL}

这些参数是从命令行获取的吗?如果是这样,那么使用argcargv: main (int argc, char *argv[])并将它们传递给一个函数来根据需要解析它们,消除对标记化的需要,并将处理多个变量参数:)

附录:从文件中读取参数:

我有几个C答案给你,取决于你希望如何实现它们,第二个示例代码只是直接读取和转储,第一个示例代码读取然后标记转储9你可以不同地使用它们这只是一个快速演示,展示如何从文件中标记参数:):

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
    FILE *f;
    int sizerValue = 1024;
    char s1[sizerValue],*p;
    f = fopen("testFile.txt", "r");
    while (fgets(s1, sizerValue, f))
    {
    while (fgets(s1, sizerValue, f))
    {
        p=strtok(s1, ";n");
        do
        {
             printf ("%sn",p);
        }
        while(p=strtok(NULL,";n"));
        }
    }
return 0;
}       
#include <stdio.h>
#define BLOCK   1024
int main() {
    FILE *f=fopen("TestFile.txt","r");
    int size;
    char buffer[BLOCK];
    while((size=fread(buffer,BLOCK,sizeof(char),f)>0)
            fwrite(buffer,size,sizeof(char),stdout);
    fclose(f);
    return 0;
}

最新更新