Is there a way to combine three or more variables with values in "int" into a string. Say i want to combine the values of a,b,c in a single string, and then further prints those values using their variables from the string.
1 Answer
To put three ints into a string:
int numbers[3] = { 1, 2, 3 };
char string[1024];
sprintf(string, "%d %d %d", numbers[0], numbers[1], numbers[2]);
The string can then be printed using normal means. sprintf() is a version of printf() that prints into a char* just as fprintf() prints to a FILE*.
As Jonathan Leffler observes, a pitfall of sprintf() is that you can overflow your char buffer. For this reason there is an snprintf() which allows you to specify a maximum length for the input:
snprintf(string, 1024, "%d %d %d", numbers[0], numbers[1], numbers[2]);
4 Comments
Jonathan Leffler
Given the size of
string, you have more than enough space to spare, but in general, using snprintf() rather than sprintf() is a good idea.Joe
I was going to say, you'd have to have quite a lot of
ULLONG_MAXes, but best use snprintf as examples to people who are new to C.Joe
50 values of 18446744073709551615 would cause problems
printf("%d,%d,%d\n", a, b, c)?