Computer Science Canada

newbie question about file streaming with variable filename.

Author:  Saad85 [ Sat Apr 05, 2008 1:25 am ]
Post subject:  newbie question about file streaming with variable filename.

okay, so to write something to a file is simple enough, but now i need to write many things to many files. the actual writing part i can deal with, but c++ gives me a compiler error when i try to open a file-out stream using a variable to hold the file name.

my code is this:
code:

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<stdlib.h>

using namespace std;

string to_string( int val )
{
stringstream stream;
stream << val;
return stream.str();
}

int main(){
        string x;
        int i=1;
        //for (i=1;i<=5;i++){
                x=to_string(i)+".txt";
                cout<<x<<endl;
               
                ofstream fout(x);
                if (fout) fout << "this writes to file";
                fout.close();
        //}
               
}




the problematic line is "ofstream fout(x);"
it works fine if i put "ofstream fout("1.txt");" but it won't let me use the variable in there. is there any way i can do this?

(as you can see, i plan to later use a for loop to do this for five seperate files)

Author:  Saad [ Sat Apr 05, 2008 9:09 am ]
Post subject:  Re: newbie question about file streaming with variable filename.

The ofstream constructor uses a C-Style string to pass the file name. Luckily the std::string class has a method to convert an std::string to a C-Style string.

You should replace
c++:
ofstream fout (x);


With

c++:
ofstream fout (x.c_str());


Some more information on c_str() method
Information on the ofstream constructor

Author:  michaelp [ Sat Apr 05, 2008 12:33 pm ]
Post subject:  RE:newbie question about file streaming with variable filename.

Also, you should change <stdlib.h> to <cstdlib>

Author:  Saad85 [ Sun Apr 06, 2008 2:36 pm ]
Post subject:  RE:newbie question about file streaming with variable filename.

ah, thanks guys


: