文章目录
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;
}
本文介绍了一种使用C++中的ifstream类从文件中读取数据的方法,详细展示了如何读取一个包含数值矩阵的文本文件,并将其加载到二维数组中。文章通过一个具体的示例,解释了文件打开、读取和关闭的过程。
1960

被折叠的 条评论
为什么被折叠?



