Concatenate string with integer

Asked

Viewed 3,328 times

1

I have a variable that is a char vector, and in this vector I need to insert a number that is an integer, searching it for 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?

1 answer

3


Can you use the snprintf as a trick to format your data, stay tuned to its parameters:

1. the buffer where to store the return of the function with the new format.

2. the buffer size to be written

3. the format of the string, the same is used in the printf()

4. your parameters that will 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

This way it is no problem if it is a number greater than 9, which it will format properly.

Ideone Exemplo

  • using sprintf doesn’t get simpler? doesn’t need to pick another string.

  • @Mathi901 http://stackoverflow.com/questions/7315936/which-of-sprintf-snprintf-is-more-secure

Browser other questions tagged

You are not signed in. Login or sign up in order to post.