文章目录
1 使用ifstream从文件中读取内容
文件map.txt的内容如下:
代码如下:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define N 64
int main(){
int nrows, ncols;
double map[N][N];
string filename;
ifstream file;
cout <<"请输入文件名.\n";
cin >> filename;
file.open(filename.c_str());
if(file.fail()){
cerr<<"打开输入文件出错.\n";
exit(1);
}
file>>nrows>>ncols;
if((nrows > N) || (ncols > N)){
cerr<<"数据太大,调整程序.\n";
exit(1);
}
//从数据文件读数据到数组
for(int i=0; i<nrows; ++i){
for(int j=0; j<ncols; ++j){
file>>map[i][j];
}
}
//关闭文件
file.close();
//结束程序
return 0;
}