#include <iostream>
#include<fstream>
#include <conio.h>
usingnamespace std;
void main()
{
int **a;
int limit;
cout<<"Enter Order Number for matrix : ";
cin>>limit;
a = newint *[limit];
for(int i=0;i<limit;i++)
a[i]=newint [limit];
int i, r, c;
r=0; c=limit/2; // limit represent columns
for(i=1; i<=(limit*limit); i++)
{
a[r][c]=i;
if(i%limit==0)
{
r++;
continue;
}
c++;
r--;
if(r<0) r=limit-1;
if(c>limit-1) c=0;
}
cout << "\n\nMagic Square of Order " << limit << " x " << limit << " is \n\n";
for(r=0; r<limit; r++)
{
for(c=0; c<limit; c++)
{
cout << a[r][c] << "\t";
}
cout << endl;
}
ofstream myfile;
myfile.open ("magic.txt");
myfile << limit<<endl;
myfile.close();
getch();
}
SO here is my magic square code and it's successful run as well , by the way
i wan to create a ofstream for it that store the input and the answer in the TXT file . can someone teach me please ? to store the answer in txt file
Example :
1 2 3 4 5 6
Enter Order Number for matrix : 3
Magic Square of order 3 x 3 is
8 1 6
3 5 7
4 9 2
and the file will be ofstream as in txt file as name magic.txt as
You're basically already doing the exact same thing, only to std::cout instead of a file:
31 32 33 34 35 36 37 38 39
cout << "\n\nMagic Square of Order " << limit << " x " << limit << " is \n\n";
for(r=0; r<limit; r++)
{
for(c=0; c<limit; c++)
{
cout << a[r][c] << "\t";
}
cout << endl;
}
I order to write that to a file at the same time, you can do:
1 2 3 4 5 6 7 8 9 10 11 12 13
ofstream os("magic.txt"); //open file for writing
cout << "\n\nMagic Square of Order " << limit << " x " << limit << " is \n\n";
for(r=0; r<limit; r++)
{
for(c=0; c<limit; c++)
{
cout << a[r][c] << "\t";
os << a[r][c] << "\t"; //write number
}
cout << endl;
os << "\n"; //new line
}
os.close(); //close file
std::cout is an object of an output stream, used to send data to the standard ouput (screen).
std::ofstream is a file output stream, used to send data to a file.
Well I don't want to just keep giving you the solutions, because that way you don't learn anything.
1 2 3 4 5 6 7 8 9 10 11 12 13
ofstream os("magic.txt"); //open file for writing
cout << "\n\nMagic Square of Order " << limit << " x " << limit << " is \n\n";
for(r=0; r<limit; r++)
{
for(c=0; c<limit; c++)
{
cout << a[r][c] << "\t";
os << a[r][c] << "\t"; //write number
}
cout << endl;
os << "\n"; //new line
}
os.close(); //close file
So after you output the square, as you did before, you ask the user if he wants to save.
If yes, you ask him for a filename.
You then create an ofstream-object that opens that file. (line 1 of example)
Then you write the output to it. (lines 3-11 of example)
Finally, you close the file (line 13 of example)
Try that and if you run into problem, feel free to come back to us with the code you have tried.