newbie question about file streaming with variable filename.
Author |
Message |
Saad85
|
Posted: 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) |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
Saad
![](http://compsci.ca/v3/uploads/user_avatars/182387547249e7ebb91fb8a.png)
|
Posted: 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
With
c++: | ofstream fout (x.c_str());
|
Some more information on c_str() method
Information on the ofstream constructor |
|
|
|
|
![](images/spacer.gif) |
michaelp
![](http://compsci.ca/v3/uploads/user_avatars/152966434478120653a049.png)
|
Posted: 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> |
|
|
|
|
![](images/spacer.gif) |
Saad85
|
Posted: Sun Apr 06, 2008 2:36 pm Post subject: RE:newbie question about file streaming with variable filename. |
|
|
ah, thanks guys |
|
|
|
|
![](images/spacer.gif) |
|
|