I have two string constants const char *
like this:
const char * p1 = "abcd";
const char * p2 = "efgh";
I want to convert these into a single s开发者_高级运维tring so that it becomes a file name:
const char * filename = "abcd_efgh.txt";
I tried to concatenate the char *
but failed. Kindly guide me as to how to do this.
Thanks
char*
are pointers, i.e they hold the address of the memory segment where the data is stored. You need to allocate a new, large enough buffer and then use the strcat()
function to concatenate the strings.
This is really the C way to do this, not the C++ way. In C++ you should use a string class, such as std::string
which handles all the buffer allocation stuff for you.
I would go with sprintf()
char buffer[strlen(p1) + strlen(p2) + 6];
sprintf(buffer, "%s_%s.txt", abcd, efgh);
(You're adding 6 for the _
, .txt
, and the \0
to terminate the string; 1 + 4 + 1)
You could use the strcat
function:
/* strcat example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
puts (str);
return 0;
}
You have declared the filename string const, which is too restrictive for what you want to do at runtime, but can be done by the pre-processor at compile time, using the adjacent string rule:
#define PART1 "abcd"
#define PART2 "efgh"
const char* p1 = PART1 ;
const char* p2 = PART2 ;
const char* filename = PART1 "_" PART2 ".txt"
However if you don't need filename to be a const
use one of the already proposed solutions.
const std::string p1 = "abcd";
const std::string p2 = "efgh";
std::string filename = p1 + "_" + p2 + ".txt";
Try this:
char name1[] = "my_demo";
char name2[] = "_file.txt";
char* filename = (char*) malloc(sizeof(char) * (strlen(name1) + strlen(name2) + 1));
strcpy(filename, name1);
strcat(filename, name2);
printf("Filename is: %s \n", filename);
free(filename);
Outputs:
Filename is: my_demo_file.txt
精彩评论