通过编写循环的方式,从文件中读取的每个数字都将分配给数组的所有元素 . 但是,当您退出 while 循环时,只会保留最后读取的数字 .
读取数字的代码需要在最里面的循环中 .
for (int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
if ( inFile >> temp )
{
temperature[i][j] = temp;
}
}
}
到达文件末尾时,您希望能够停止进一步尝试阅读 . 最好使用函数读取数据并在达到EOF时从函数返回,或者在读取数据时有任何其他类型的错误 .
在此期间,您也可以使用函数来打印数据 .
#include
#include
const int row = 20;
const int column = 5;
using namespace std;
int readData(ifstream& inFile, double temperature[row][column])
{
for (int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
double temp;
if ( inFile >> temp )
{
temperature[i][j] = temp;
}
else
{
return i;
}
}
}
return row;
}
void printData(double temperature[][column], int numRows)
{
for(int i=0; i
{
for(int j=0; j
{
cout << temperature[i][j] << " ";
}
cout << endl;
}
}
int main()
{
ifstream inFile;
inFile.open("grades1.txt");
if (inFile)
{
double temperature[row][column] = {};
int numRows = readData(inFile, temperature);
printData(temperature, numRows);
}
}