I am trying to open a file in fstream with an integer as part of the name. The integer is a variable that needs to be able to be changed. So i can open files like "1.txt", "2.txt" and so on.
Kind of what I am trying now:
fstream outfile;
int i;
for(i=0;i%26lt;10;i++)
{
outfile.open( ( i + ".txt"), fstream::app);
//do stuff to outfile
outfile.close();
}
C++ fstream help?
mapaghimagsik gives some good advice in using stringstream and normally I prefer the C++ way but sometimes falling back to the old C way is shorter.
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
#include %26lt;fstream%26gt;
using namespace std;
int main()
{
char filename[20];
fstream outfile;
for (int i = 0; i %26lt; 10; ++i)
{
sprintf(filename, "%d.txt", i);
outfile.open(filename, ios::out | ios::app);
if (! outfile)
{
cout %26lt;%26lt; "error opening " %26lt;%26lt; filename %26lt;%26lt; endl;
}
//do stuff to outfile...
outfile.close();
}
}
Reply:You need to convert i to a string to concatenate
std::stringstream str(std::stringstream::in);
std::stringstream s (std::stringstream::in | std::stringstream::out);
std::string s1;
s %26lt;%26lt; 1 %26lt;%26lt; ".txt";
s %26gt;%26gt; s1;
std::cout %26lt;%26lt; s1%26lt;%26lt; std::endl;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment