strcat() for formatted strings

前端 未结 6 1473
予麋鹿
予麋鹿 2021-02-20 05:37

I\'m building a string piece by piece in my program and am currently using a mix of strcat() when I\'m adding a simple string onto the end, but when im adding a formatted string

6条回答
  •  余生分开走
    2021-02-20 05:56

    Write your own wrapper for your need.

    A call to this would look like this :-

    result = universal_concatenator(4,result,"numbers are %d %f\n",5,16.045);  
    result = universal_concatenator(2,result,"tail_string");
    

    You could define one function, that would take care of worrying about, if you need to use sprintf() or strcat(). This is what the function would look like :-

    /* you should pass the number of arguments
     * make sure the second argument is a pointer to the result always
     * if non formatted concatenation:
     *         call function with number_of_args = 2
     * else
     *         call function with number of args according to format
     *         that is, if five inputs to sprintf(), then 5.
     *
     * NOTE : Here you make an assumption that result has been allocated enough memory to
     *        hold your concatenated string. This assumption holds true for strcat() or
     *        sprintf() of your previous implementation 
     */
    
    char* universal_concaternator(int number_of_args,...)
    {
      va_list args_list;
      va_start(args_list,number_of_args);
      int counter = number_of_args;
      char *result = va_arg(args_list, char*);
      char *format;
      if(counter == 2) /* it is a non-formatted concatenation */
      {
          result = strcat(result,va_arg(args_list,char*));
          va_end(args_list);
          return result;
      }
      /* else part - here you perform formatted concatenation using sprintf*/
      format = va_arg(args_list,char*);
      vsprintf(result + strlen(result),format,args_list);
      va_end(args_list);
      return result; 
    }
    
    /* dont forget to include the header 
     *  #FOR-ANSI 
     * or  #FOR-UNIX
     */ 
    

    It should firstly, determine, which of the two it should call(strcat or sprintf), then it should make the call, and make it easy for you to concentrate on the actual logic of whatever you are working on! Just ctrl+c code above and ctrl+v into your code base.

    Note : Matt's answer is a good alternative for long strings. But for short string lengths(<250), this should do.

提交回复
热议问题