Search code examples
stringstaticappendfstream

Combining a static char* and a constant string


I want to be able to append a constant string to the end of another string in the form of a char*, and then use the resulting string as an argument for open(). Here's what it looks like:

file1.cpp

#include "string.h"

file2 foo;

char* word = "some";
foo.firstWord = word; //I want the file2 class to be able to see "some"

file2.h

#include <fstream>
#include <iostream>

#define SECONDWORD "file.txt"

class file2{
public:
    file2();
    static char* firstWord;
    static char* fullWord;

private:
    ofstream stream;

}

file2.cpp

#include "file2.h"

char* file2::firstWord;
char* file2::fullWord;

fullWord = firstWord + SECONDWORD; //so fullWord is now "somefile.txt" ,I know this doesn't work, but basically I am trying to figure out this part

file2::file2(){
    stream.open(fullWord);
}

So I am not very well versed in C++, so any help would be appreciated!


Solution

  • C++-style solution might be the following.

    #include <string>
    
    char* a = "file";
    char* b = ".txt";
    
    ...
    
    stream.open((std::string(a) + b).c_str());
    

    What happens here? First, std::string(a) creates a temporary std::string object. Than b value is added to it. At last, c_str() method returns a c-style string which contains a + b.