java 二维数组添加_如何从文件内容添加到二维数组?

通过编写循环的方式,从文件中读取的每个数字都将分配给数组的所有元素 . 但是,当您退出 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值