Question

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?

Était-ce utile?

La 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;
}

Autres conseils

You will get a string version of the variable's name, i.e. it will convert a to "a". The #when used like this is called the stringification operator.

For example:

#define TO_STRING(val) #val

int main(void)
{
  const int a = 12;
  print("a is %s\n", TO_STRING(a));
  return 0;
}

This will print a is a.

What do you expect to happen?

You can't get the variable's value, of course, since that's not available when the pre-processor runs (which is at compile-time).

try this will work with integers: edit the format string for other data types.

sprintf(str,"%d",value);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top