Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding to a string

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
0
0
GB
Hello everyone,

How do I conatecate a string in C?

I have tried

string = "text" + var1 + "moretext" +var2;

but this dosen't work. I think this works in C++ but not in C? Any ideas?

jim
 
sorry...i forgot to mention i need to be able to do this without using <string.h> - does anyone know the source code that string.h uses for the strcat function?

cheers

jim
 
Easiest way would be to use the snprintf function. It basically prints to a buffer in memory instead of the screen.

Code:
int snprintf ( char *str, size_t n,
               const char *format, ... );

(The string would have to be of type char*, not const char*, and I'm assuming var1 and var2 are integers)
In your case, you could have:

Code:
snprintf(string,MAX_STRING_LENGTH, &quot;%s%d%s%d&quot;,&quot;text&quot;,var1,&quot;moretext&quot;,var2);
 
This way is very simple to,just look:

#include <stdio.h>
void main()
{
char var1[16]={&quot;text&quot;};
char var2[9]={&quot;moretext&quot;};
char string[16]={&quot;&quot;};

//first way to do it
sprintf(string,&quot;%s%s&quot;,var1,var2);
printf(&quot;%s&quot;,string);

printf(&quot;\n\n&quot;);//skip lines
//second way
strcat(var1,var2);
printf(&quot;%s &quot;,var1);
}
 
You'll need to add the header <string.h>,in order to make the compiler recognize the fonction &quot;strcat&quot;;
 
Hi,

Here's the code for strcpy (renamed to mystrcpy for avoiding compilation conflicts!)

Code:
void mystrcpy(char *dStr, char *sStr)
{
	while (*dStr++);
dStr--;
	while(*(dStr++)=*(sStr++));	
}

Let me know if u used it.

have fun coding...

J Roy. :)
user.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top