c语言如何从文件中读入矩阵,存入二维数组?

如题。最好给个完整的代码。

#include<iostream>
using namespace std;
int mat[101][101];
int main()
{
int n,m;//行,列...
int i,j;
freopen("D:\\in.txt","r",stdin);//读文件...
cin>>n>>m;//读入矩阵行数,列数...
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cin>>mat[i][j];
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-03-29
这要看你的文件中数据是这么存的,例如,如果是在.TXT文档中一行一行的矩阵,那即很简单,直接读,并转换数据类型。。

你最好给个事例文件。。。
第2个回答  2019-07-19
C++代码:
需要手动输入文件路径,以及文件中每一行有几列,读取额数据存入一个向量中,可视为二维数组。
#include
#include
#include
#include
using
namespace
std;
int
read_scanf(const
string
&filename,const
int
&cols,vector
&_vector)
//
功能:将filename
中的数据(共cols列)读取到_vector中,_vector可视为二维数组
{
FILE
*fp=fopen(filename.c_str(),"r");
bool
flag=true;
int
i=0;
if(!fp){
cout<<"File
open
error!\n";
return
0;
}
while(flag)
{
double
*point=new
double[cols];
for(i=0;i
output_vector;
if(!read_scanf(file,columns,output_vector))return;
//output_vector可视为二维数组;输出数组元素:
int
rows=output_vector.size();
for(int
i=0;i
评论
0
0
0
加载更多
第3个回答  推荐于2016-01-23
C++代码:
需要手动输入文件路径,以及文件中每一行有几列,读取额数据存入一个向量中,可视为二维数组。
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
using namespace std;

int read_scanf(const string &filename,const int &cols,vector<double *> &_vector)
// 功能:将filename 中的数据(共cols列)读取到_vector中,_vector可视为二维数组
{
FILE *fp=fopen(filename.c_str(),"r");
bool flag=true;
int i=0;
if(!fp){ cout<<"File open error!\n"; return 0; }
while(flag)
{
double *point=new double[cols];
for(i=0;i<cols;i++) //读取数据,存在_vector[cols]中
{
if(EOF==fscanf(fp,"%lf",&point[i])){flag=false;break;};
if(EOF==fgetc(fp)){flag=false;i++;break;}
}
if(cols==i)_vector.push_back(point);
}
fclose(fp);
return 1;
}
void main()
{
string dir="E:/";
string file=dir+"test.txt";
//txt文件中有4列
int columns=4;
vector<double *> output_vector;
if(!read_scanf(file,columns,output_vector))return;
//output_vector可视为二维数组;输出数组元素:
int rows=output_vector.size();
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++){cout<<output_vector[i][j]<<" ";}
cout<<endl;
}

system("pause");
return;
}

验证:
E:/test.txt 内容(空格可换为逗号,分号等):
81.081 0.000 39.420 255
80.954 0.000 38.441 255
83.890 0.000 31.327 255
84.061 0.000 31.097 255
84.120 0.000 31.045 160
84.120 0.000 31.045 160
程序输出:
81.081 0 39.42 255
80.954 0 38.441 255
83.89 0 31.327 255
84.061 0 31.097 255
84.12 0 31.045 160
84.12 0 31.045 160
相似回答