Search code examples
c++filenamesofstream

ofstream variable in name


I'm trying to create an ofstream and then write values from an array into it.

void Graph::toFile(char* filename)
{
    ofstream outfile(filename.c_str()+"_new.txt");
    for(int i = 0; i < noOfVertices; i++)
        outfile << graphPartition[i] << endl;
    outfile.close();
}

My main problem is, that I want the output file to be named filename+"new.txt". However, there is something wrong with my approach, because i keep getting an error expression must have class type.

I'm really sorry, if this question is a duplicate, I haven't found an satisfying solution.


Solution

  • Your problem is that filename is not std::string it's a c-string (char*). C-strings are not objects, they don't have methods, they're just a pointer to a zero-terminated array of characters in memory.

    filename.c_str()
           -^-
    

    The second problem you'd have with this approach, if filename was a std::string, is that adding two C-string pointers doesn't concatenate the strings, it simply does math on the pointers, giving you an address equal to the address returned by filename.c_str() plus the address of "_new.txt"

    If you change your code to receive the filename as a std::string

    void Graph::toFile(std::string filename)
    

    then you can do the following:

    filename += "_new.txt";
    

    As follows:

    void Graph::toFile(std::string filename)
    {
        filename += "_new.txt";
        ofstream outfile(filename.c_str());
    

    or

    void Graph::toFile(std::string filename)
    {
        ofstream outfile(filename + "_new.txt");
    

    Demo:

    #include <iostream>
    #include <string>
    
    
    void Graph_toFile(std::string filename)
    {
        filename += "_new.txt";
        std::cout << "opening " << filename << "\n";
    }
    
    int main() {
        Graph_toFile("hello_world");
    
        return 0;
    }
    

    http://ideone.com/eAnfZQ