143

I have a private class variable char name[10] to which I would like to add the .txt extension so that I can open the file present in the directory.

How do I go about this?

It would be preferable to create a new string variable that holds the concatenated string.

roschach
  • 8,390
  • 14
  • 74
  • 124
Slashr
  • 3,139
  • 6
  • 18
  • 13

8 Answers8

213

First of all, don't use char* or char[N]. Use std::string, then everything else becomes so easy!

Examples,

std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!

Easy, isn't it?

Now if you need char const * for some reason, such as when you want to pass to some function, then you can do this:

some_c_api(s.c_str(), s.size()); 

assuming this function is declared as:

some_c_api(char const *input, size_t length);

Explore std::string yourself starting from here:

starball
  • 20,030
  • 7
  • 43
  • 238
Nawaz
  • 353,942
  • 115
  • 666
  • 851
40

Since it's C++ why not to use std::string instead of char*? Concatenation will be trivial:

std::string str = "abc";
str += "another";
nogard
  • 9,432
  • 6
  • 33
  • 53
  • 3
    Worth noting, the trivial use comes with a non-trivial price tag with respect to runtime performance. Worst case is, that `operator+=` performs both a deallocation and an allocation. Heap allocations are among the most expensive operations we commonly do. – IInspectable Feb 07 '20 at 12:17
23

If you were programming in C, then assuming name really is a fixed-length array like you say, you have to do something like the following:

char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...

You see now why everybody recommends std::string?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
TonyK
  • 16,761
  • 4
  • 37
  • 72
  • 1
    Don't you think this answer is irrelevant for this question? – IcyFlame Mar 10 '13 at 07:33
  • 18
    I do think this is relevant since "the guy" is using char instead of std::string. Furthermore, it shows an explicit way of concatenating that was not showed in the most voted answer. At least I learned something with it. – gvegayon Aug 30 '17 at 21:55
  • 1
    This also shows a method of doing a string concatenation without dynamic memory allocation. Unless I am wrong, std::string operator += requires a possible reallocation. – Ashley Duncan May 19 '19 at 22:11
  • As of 9th March 2023, this answer is *absolutely* relevant. Thanks @TonyK! (I am working on an old project that primarily uses C.) – Ed Graham Mar 09 '23 at 12:05
8

There is a strcat() function from the ported C library that will do "C style string" concatenation for you.

BTW even though C++ has a bunch of functions to deal with C-style strings, it could be beneficial for you do try and come up with your own function that does that, something like:

char * con(const char * first, const char * second) {
    int l1 = 0, l2 = 0;
    const char * f = first, * l = second;

    // find lengths (you can also use strlen)
    while (*f++) ++l1;
    while (*l++) ++l2;

    // allocate a buffer including terminating null char
    char *result = new char[l1 + l2 + 1];

    // 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");

... the result of which is file_name.txt.

You might also be tempted to write your own operator + however IIRC operator overloads with only pointers as arguments is not allowed.

Also, don't forget the result in this case is dynamically allocated, so you might want to call delete on it to avoid memory leaks, or you could modify the function to use stack allocated character array, provided of course it has sufficient length.

Warren Seine
  • 2,311
  • 2
  • 25
  • 38
dtech
  • 47,916
  • 17
  • 112
  • 190
  • See my comment to IcyFlame's answer. – TonyK Mar 10 '13 at 07:25
  • 3
    There is also `strncat()` function that is usually better alternative – nogard Mar 10 '13 at 07:25
  • @nogard: `strncat` is irrelevant here, because we already know the length of the second parameter `".txt"`. So it would just be `strncat(name, ".txt", 4)`, which doesn't gain us anything. – TonyK Mar 10 '13 at 07:44
4

C++14

std::string great = "Hello"s + " World"; // concatenation easy!

Answer on the question:

auto fname = ""s + name + ".txt";
273K
  • 29,503
  • 10
  • 41
  • 64
0

strcat(destination,source) can be used to concatenate two strings in c++.

To have a deep understanding you can lookup in the following link-

http://www.cplusplus.com/reference/cstring/strcat/

Madhurya Gandi
  • 895
  • 8
  • 13
0

It is better to use C++ string class instead of old style C string, life would be much easier.

if you have existing old style string, you can covert to string class

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
    string trueString = string (greeting);
    cout << trueString + "and there \n"; // compiles fine
    cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too
i.AsifNoor
  • 587
  • 5
  • 14
-2
//String appending
#include <iostream>
using namespace std;

void stringconcat(char *str1, char *str2){
    while (*str1 != '\0'){
        str1++;
    }

    while(*str2 != '\0'){
        *str1 = *str2;
        str1++;
        str2++;
    }
}

int main() {
    char str1[100];
    cin.getline(str1, 100);  
    char str2[100];
    cin.getline(str2, 100);

    stringconcat(str1, str2);

    cout<<str1;
    getchar();
    return 0;
}
Daniel Ryan
  • 6,976
  • 5
  • 45
  • 62
Kartik
  • 9
  • 2