Concatenate string with integer

1

I have a variable that is a vector of char, and in this vector I need to insert a number that is an integer, fetching it from another variable:

int quantidade;
char id[3] = 'p';

For example, if the quantity is 2, I need the string id to be "p2". How can I do this?

    
asked by anonymous 29.06.2015 / 01:17

1 answer

3

You can use snprintf as a trick to format your data, stay tuned to its parameters :

1. the buffer where it will save the function return with the new formatting.

2. the size of the buffer to be written

3. the formatting of the string, equal is used in printf()

4. your parameters to be added in formatting

int quantidade = 2;
char id[3] = "p";
char novoId[10];

snprintf (novoId, 10, "%s%d", id, quantidade );
printf("%s", novoId);
  

p2

That way no problem if it is a number greater than 9, that it will format correctly.

IdeOne Example

    
29.06.2015 / 01:52