1

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.

2
  • 2
    It is not very clear what you want in the second part of the question. Please give some simple example. Commented Sep 26, 2013 at 15:03
  • 1
    Do you just mean printf("%d,%d,%d\n", a, b, c)? Commented Sep 26, 2013 at 15:08

1 Answer 1

8

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]);
Sign up to request clarification or add additional context in comments.

4 Comments

For further information consult the sprintf page at cplusplus.com.
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.
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.
50 values of 18446744073709551615 would cause problems

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.