There is a strcat () function from the ported C library that will concatenate the "C style string" string for you.
By the way, although C ++ has a bunch of functions for working with C-style strings, it may be useful if you try to find your own function that does this, for example:
char * con(const char * first, const char * second) { int l1 = 0, l2 = 0; const char * f = first, * l = second; // step 1 - find lengths (you can also use strlen) while (*f++) ++l1; while (*l++) ++l2; char *result = new char[l1 + l2]; // then concatenate for (int i = 0; i < l1; i++) result[i] = first[i]; for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1]; // finally, "cap" result with terminating null char result[l1+l2] = '\0'; return result; }
... and then...
char s1[] = "file_name"; char *c = con(s1, ".txt");
... whose result is file_name.txt .
You might also be tempted to write your own operator + , but only overload the IIRC operator with pointers, because the arguments are not allowed.
Also, do not forget that the result is dynamically allocated in this case, so you may want to delete it to avoid memory leaks, or you can change the function to use the character array allocated by the stack, provided that it has sufficient length.
dtech Mar 10 '13 at 7:18 2013-03-10 07:18
source share