我正在编写代码来读取一组数字,然后将它们显示在屏幕上的 4x4 网格中,然后程序将确定它是否是幻方。我的问题是如何让用户将数字输入到 readData 方法中显示的文件中,以便在调用该方法时显示用户网格。
文件 data.txt 也存储在哪里?
谢谢
#include<iostream>
#include<fstream>
using namespace std;
const int dimension = 4; // dimension for the array
typedef int Sq[dimension] [dimension]; // declare vector for type names
void ReadData(Sq square ) // read data from file
{ ifstream inFile;
char fileName[13] = "data.txt";
inFile.open (fileName); // open file for reading
for (int r = 0; r < dimension; r++) // row loop
for ( int c = 0; c < dimension; c++) // column loop
inFile >> square[r][c]; // read data into matrix
inFile.close( ); // close the file
}
void Display ( const Sq square ) // display matrix
{ cout << " Magic Square Program " << endl << endl;
for (int r = 0; r < dimension; r++)
{ for ( int c = 0; c < dimension; c++)
{ cout.width(6); //set output width to 6 characters
cout << square[r][c] << "\t "; // display numbers
}
cout << endl;
}
}
bool magicSquare( Sq square) // add rows, columns, and diagonals
{ int firstSum = 0, sum;
bool magic = true;
for (int r = 0; r < dimension; r++) // add 1st column for a comparison
firstSum += square[r][1];
for (int r = 1; r < dimension; r++) // row loop first when adding rows
{ sum = 0;
for ( int c = 0; c < dimension; c++)
sum += square[r][c]; // add row
if ( sum != firstSum) // check for magic failure
return (false); // not magic
}
for ( int c = 0; c < dimension; c++) // column loop first when adding columns
{ sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][c]; // add columns
if ( sum != firstSum) // check for magic failure
return (false); // not magic
}
sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][r]; // add front diagonal
if ( sum != firstSum) // check for magic failure
return (false); // not magic
sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][dimension - r - 1]; // add back diagonal
if ( sum != firstSum) // check for magic failure
return (false); // not magic
else
return (true);
} // end magicSquare function
int main( )
{
Sq square;
ReadData( square); // read data from file
Display ( square); // display matrix
if ( magicSquare(square) ) // check for magic property
cout << "\n This Square is Magic \n " << endl;
else
cout << "\n This Square is Not Magic \n " << endl;
system("Pause");
return(0);
}