Hi, I'm trying to create a quick and small programs that works when you press F9, it should create files on my desktop using "ofstream" from A to Z. I can't get it to run when i put ofstream in a for cycle. Here is the code to see it better.

#include <cstdlib.h>
#include <iostream.h>
#include <conio.h>
#include<fstream.h>
//------------------
void main()
{
int i;
char letras[3];
letras[0]='a';
letras[1]='b';
letras[2]='c';

for(i=0;i<3;i++)
ofstream print(letras);

}

thanks you so much for any help.

Recommended Answers

All 4 Replies

The parameter to open() has to be a null-terminated character array (commonly called a string). All you are trying to send it is a single character. Try this:

int main()
{
int i;
char* letras[3] = {"a","b","c"};

for(i=0;i<3;i++)
{
    ofstream print(letras[i]);
}

}

An ofstream is an object, not a function.
To open a file using ofstreams you first create the object, then open the file. Like so:

ofstream file;
file.open("a.txt");
//Do something
file.close();

In your case you could place it in a loop. You'll have to make a string object to get the name of the file right.
Oh, the open function requires a cstring, not a standard string.

thanks for the help! it solved my problem.

#include <fstream>
#include <string>
int main() {
   for ( char ch = 'A'; ch <= 'Z'; ch++ ) {
      std::string fn = ch + std::string(".txt");
      std::ofstream file(fn.c_str());
   }
   return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.