Search code examples
cstringstringifystringification

Convert any variable to string in C


Is is possible to convert any variable of any type to string?

I wrote the following

#define TO_STRING(val) #val

Is this a valid way of converting a variable into a string?


Solution

  • I think the code below will do your work. I uses the standard sprintf function, which prints data from any type to a string, instead to stdout. Code:

    #include <stdio.h>
    
    #define INT_FORMAT "%d"
    #define FLOAT_FORMAT "%f"
    #define DOUBLE_FORMAT "%lf"
    #define LL_FORMAT "%lld"
    // ect ...
    
    #define CONVERT_TO_STRING(FORMAT, VARIABLE, LOCATION) \
      do { \
        sprintf(LOCATION, FORMAT, VARIABLE); \
      } while(false)
    
    int main() {
      char from_int[30];
      char from_float[30];
      char from_double[30];
      char from_ll[30];
    
      CONVERT_TO_STRING(INT_FORMAT, 34, from_int);
      CONVERT_TO_STRING(FLOAT_FORMAT, 34.234, from_float);
      CONVERT_TO_STRING(DOUBLE_FORMAT, 3.14159265, from_double);
      CONVERT_TO_STRING(LL_FORMAT, 9093042143018LL, from_ll);
    
      puts(from_int);
      puts(from_float);
      puts(from_double);
      puts(from_ll);
    
      return 0;
    }