简体   繁体   English

将具有可变数量参数的函数中的文本与数字连接

[英]Concatenate text with numbers in a function with variable number of parameters

I made a function in C, that concatenates a variable number of strings. 我用C语言编写了一个函数,该函数连接了可变数目的字符串。 That's my code: 那是我的代码:

char* texto(const char* s, ...){
        va_list args;
        char *tmp;
        char *res;
        size_t len = strlen(s);

        // pega um handle ao início da lista de parâmetros
        va_start(args, s);
        // calcula o tamanho total de todas as strings - pega o próximo parâmetro da lista, até chegar no NULL
        while ((tmp = va_arg(args, char*))){
            len += strlen(tmp);
        }
        va_end(args);

        res = malloc(len+1);
        if (!res){
                fprintf(stderr, "Erro ao alocar string. Função 'texto'\n");
                exit(EXIT_FAILURE);
        }

        // cria a string concatenada
        strcpy(res, s);

        va_start(args, s);
        // pega o próximo parâmetro da lista, até chegar no NULL
        while ((tmp  = va_arg(args, char*))){ 
            strcat(res, tmp); 
        }
        va_end(args);

        return res;
}

I'm using like this: 我正在这样使用:

char* txt = texto("a", "b", "c", "d", "e", NULL);
//txt is now: "abcde"

It works fine. 工作正常。 But I can't pass numeric parameters to this function, only strings. 但是我不能将数字参数传递给此函数,只能传递字符串。 I need to change the function to work like this: 我需要更改功能才能像这样工作:

char* txt = texto("a", "b", 1, "d", 4.5, "e", NULL);
//txt is now: "ab1d4.5e"

How can I do that? 我怎样才能做到这一点? How I get parameters with diferent types using va_arg()? 如何使用va_arg()获取具有不同类型的参数?

The solution I found until now is create a function int2str(): 我到目前为止发现的解决方案是创建一个函数int2str():

inline char* int2str(int inteiro){
    char* str = malloc(10);
    sprintf(str, "%d", inteiro);
    return str;
}

But I have to use this way: 但是我必须使用这种方式:

char* txtnum = int2str(23);
char* txt = texto("a", txtnum, NULL);
free(txtnum);

otherwise, I got a memory leak... 否则,我会发生内存泄漏...

I could use the function int2str() inside the function texto() but I don't know how to check the type of the parameters! 我可以在texto()函数中使用int2str()函数,但我不知道如何检查参数的类型!

Ps.: I'm using C, not C++ for my code. 附言:我的代码不是C ++,而是C语言。

How can I do that? 我怎样才能做到这一点? How I get parameters with diferent types using va_arg()? 如何使用va_arg()获取具有不同类型的参数?

Unfortunately this is not possible, the type information gets lost when you are using variable argument lists. 不幸的是,这是不可能的,当您使用变量参数列表时,类型信息会丢失。

One quite easy solution is to use a format string which declares the "types", but then again, why don't you simply use the standard function snprintf ? 一个很简单的解决方案是使用一个声明“类型”的格式字符串,但是,为什么不简单地使用标准函数snprintf呢? Reference here . 参考这里

char buffer[256];
snprintf(buffer, sizeof(buffer), "%s%s%d%s%f%s", "a", "b", 1, "d", 4.5, "e", NULL);

If you're willing to take a gcc specific solution you can change int2str to be this macro: 如果您愿意采用特定于gcc的解决方案,则可以将int2str更改为以下宏:

# define int2str(i)                                                           \
  (__extension__                                                              \
    ({                                                                        \
      char *new = (char *) __builtin_alloca (10);                        \
      sprintf(new, "%d", i); \
      new;                                  \
    }))

This then means you can write: 这意味着您可以编写:

char* txt = texto("a", int2str(23), NULL);

without leaking. 没有泄漏。 It's very non portable though. 这是非常不便携虽然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM