strcat() int variable + C

31.2k views Asked by At

I need to print something on this form:

[1] "text"
[2] "text"
[3] "text"

I'm using strcat(), so I want to concatenate "text" to a buffer.
I get "text" one element at a time in a buffer, and I need to concatenate it to a string.

The problem is that I can't seem to figure out how to get the [number] part in the front.

First, is it possible to strcat() an int?
I have tried, but can't seem to get it to work.

Second, is it possible to get the '[' ']' around the variable? (I need the int value to increase for each loop).
This may be a stupid question, but I really can't figure out how to solve this, and I need the menu to be on this form or something similar.

3

There are 3 answers

2
Matheus Portela On BEST ANSWER

First of all, try sprintf to put your integer into a buffer string. Then, concatenate this string with the one you wanted.

Something like this:

char string[STRING_SIZE] = "text "
char buffer[BUFFER_SIZE];
sprintf(buffer, "%d", number);
strcat(string, buffer)

Adjust the sizes for your situation.

0
Wang On

You can use a counter to know the number for each string of text :

char    buffer[BUFFER_SIZE];
int     counter = 1;

while (/* condition for continuing reading buffer */) {
    buffer = //readBuffer();
    printf("[%d] %s ", counter, buffer);
    counter++;
}
printf("\n");
2
Anthony JEAMME On

First, is it possible to strcat() an int?

No, you have to convert the int in char *. Look at the following implementation : http://www.opensource.apple.com/source/groff/groff-10/groff/libgroff/itoa.c.

Second, is it possible to get the '[' ']' around the variable?

Just use strcat to add this

strcat( buffer, text1 );
strcat( buffer, "[" )
// ...