Change C++ to files

I have the following question for a class:
Write a program that asks the user for a positive integer no greater than 15. The program should then store a square on a file using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program store the following pattern in a file named “pattern.dat”:

XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
The program should then read the stored pattern from the file you just created and display the pattern on the screen.

I can write the program in c++, but it's just a bonus, and I dont know how to write it in files( with #include<fstream>). Any help would be appreciated. This is my program.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int a, b, c;
cout<<"Enter the number"<<endl;
cin>>a;
if(a<15&&(a>0))
{
for(b=1;(b<=a);++b)
{
for(c=1;(c<=a);++c)
cout<<"x";

cout<<"\n";
}
system("pause");
}
else
cout<<"error\n";
return 0;
}
closed account (E0p9LyTq)
You already did most of the work. Now instead of doing I/O to the console you modify the program to output to a file.

C++ automatically creates a console output object for you (std::cout). With file streams you have to explicitly create the output object, specifying a filename. Using the same syntax as std::cout you can write your output to a file.

You can read about file output streams, with examples, here:

http://www.cplusplus.com/reference/fstream/ofstream/
Topic archived. No new replies allowed.