How can I append “.txt” to a private char array in C++?

I have a private class variable char name[10] and I want to add the .txt extension to it so I can open the corresponding file in the directory. I’d prefer to create a new string variable that holds the concatenated result. How can I perform string concatenation in C++ in this case?

I’ve done this plenty of times :sweat_smile:. Since your variable is a char array, you can use strcat from <cstring>:

#include <iostream>
#include <cstring>

class MyClass {
private:
    char name[10] = "file1";
public:
    void printFileName() {
        char filename[20]; // make sure it’s big enough
        strcpy(filename, name);    // copy the original name
        strcat(filename, ".txt");  // append .txt
        std::cout << filename << std::endl;
    }
};

int main() {
    MyClass obj;
    obj.printFileName();
}

Important: Make sure the target array (filename) is big enough to hold the original string + extension + null terminator.

I usually make it a bit larger to avoid accidental overflow.

I personally prefer using std::string whenever possible, it’s safer and easier to work with:

#include <iostream>
#include <string>

class MyClass {
private:
    char name[10] = "file1";
public:
    void printFileName() {
        std::string filename = std::string(name) + ".txt";
        std::cout << filename << std::endl;
    }
};

int main() {
    MyClass obj;
    obj.printFileName();
}

Converting char[] to std::string allows easy concatenation using +.

No need to worry about array sizes or buffer overflow. I use this approach in almost all modern C++ code.

If you want a C-style approach but with safety, snprintf is a nice option:

#include <iostream>
#include <cstdio>

class MyClass {
private:
    char name[10] = "file1";
public:
    void printFileName() {
        char filename[20];
        snprintf(filename, sizeof(filename), "%s.txt", name);
        std::cout << filename << std::endl;
    }
};

int main() {
    MyClass obj;
    obj.printFileName();
}

snprintf ensures you won’t write past the buffer size, avoiding common bugs.

I usually use this when working in embedded systems or older codebases that avoid std::string.