Reputation: 3327
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?
Upvotes: 3
Views: 14459
Reputation: 9073
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;
}
Upvotes: 3
Reputation: 2303
try this will work with integers: edit the format string for other data types.
sprintf(str,"%d",value);
Upvotes: 3
Reputation: 400109
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).
Upvotes: 3