Adding an integer to a C-string

duragezic

Lifer
Oct 11, 1999
11,234
4
81
I don't know. I can't think of how to do this. It must be very simple.

I have an integer variable holding some number, say from 1 to 50, that gets incremented with each new message.

Currently, I store a copy of some C-strings combined into a single C-string as an element in an array of C-strings using strcat().

For example, I have

char *msg1 = "this is"
char *msg2 = "a msg"

then I do

strcat(messages[idx], msg1)
strcat(messages[idx], msg2)

so then messages[idx] reads "this is a msg"

But I want to use that integer variable so that the element in 'messages' reads

"i: this is a msg"

where i is the actual value of that integer variable. I see some string to double or integer functions in string.h, and this would all be much easier with a C++ String, but I don't know.. I'm just not finding a way to do this. Any ideas?
 

duragezic

Lifer
Oct 11, 1999
11,234
4
81
It says its a non-standard function supported by only some C compilers.

I have included <stdio.h> and <stdlib.h> for other things I needed already, but there's a compiler error of

main.o(.text+0x2a1): In function `storeCmd':
/major/swcarlso/cs4411/project1/main.c:130: undefined reference to `itoa'


So the compiler I have to use doesn't support it?
 

clamum

Lifer
Feb 13, 2003
26,252
403
126
Try sprintf or whatever that function is that lets you format printing to standard out.
 

you2

Diamond Member
Apr 2, 2002
6,735
1,764
136
To be safe you want snprintf (not that it is relevant to your program). man snprintf should tell you everything you need to know...
 

xtknight

Elite Member
Oct 15, 2004
12,974
0
71
Yeah, using strcat is a waste of time when you have functions like sprintf. Its counterpart snprintf prevents buffer overflows if used properly. (strncat is the safe strcat version.)

sprintf(targetvar, "%d: %s", 5, "here is a string");

targetvar will then be: "5: here is a string\0"
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
char buffer[255]
sprintf (buffer,%d: %s %s",value,msg1, msg2);