如下所示,请问该怎样将一个在txt里的2维数组提取进C++程序?

比如一个10X10的数组,double的,提取到a[10][10]中。
我之后的运算要用到这个数组,所以不能只是cout出来,a[10][10]一定要等于那个数组。

繁星coding
浏览 85回答 3
3回答

蛊毒传说

假设二维数组以行优先的方式存放在外部文件中。&nbsp;#include <fstream>&nbsp;#include <iostream>&nbsp;using namespace std;const int s = 10; //数组为 10X10int myarray[s][s];//定义二维数组void main()&nbsp;{&nbsp;ifstream inobj("array.txt");if (!inobj)&nbsp;{&nbsp;cout << "file open failed.\n";&nbsp;exit(0);&nbsp;}&nbsp;for (int i = 0; i < s; ++i)&nbsp;{&nbsp;if (inobj.eof())&nbsp;break;for (int j = 0; j < s; ++j)&nbsp;{&nbsp;&nbsp;inobj >> myarray[i][j];&nbsp;}&nbsp;}&nbsp;cout << endl;&nbsp;inobj.close();&nbsp;//现在,二维数组 myarray 已经用文件初始化了,每一个元素都具有有效值cout<<"the array:\n";for (int m = 0; m < s; ++m)&nbsp;{&nbsp;for (int n = 0; n < s; ++n)&nbsp;{&nbsp;cout<<myarray[m][n]<<"\t";}cout<<"\n";}&nbsp;cout<<"\n";}

红糖糍粑

c语言可以存入以逗号隔开的数据,c++我只知道可以存入以空格隔开的数据,你把数据用空格隔开才可以用下面的程序编译。&nbsp;#include<fstream>&nbsp;#include<iostream>&nbsp;using namespace std;&nbsp;struct list&nbsp;{&nbsp;int num;&nbsp;float x_coor;&nbsp;float y_coor;&nbsp;float z_coor;&nbsp;};&nbsp;int main()&nbsp;{&nbsp;int n = 0,i=0,count=0;&nbsp;list a[10];&nbsp;ifstream fin("hello.txt");&nbsp;if(!fin)&nbsp;{&nbsp;cout<<"open failed!"<<endl;&nbsp;exit(1);&nbsp;}&nbsp;while(fin>>a[i].num>>a[i].x_coor>>a[i].y_coor>>a[i].z_coor)&nbsp;{&nbsp;//cout<<a[i].num<<" "<<a[i].x_coor<<" "<<a[i].y_coor<<" "<<a[i].z_coor<<endl;&nbsp;i++;&nbsp;count++;&nbsp;}&nbsp;fin.close();&nbsp;for(i=0;i<count;i++)&nbsp;cout<<a[i].num<<" "<<a[i].x_coor<<" "<<a[i].y_coor<<" "<<a[i].z_coor<<endl;&nbsp;return 0;&nbsp;}&nbsp;

沧海一幻觉

文件中的数字以空格分开。#include <fstream>#include <iostream>#include <string>#define N 10using namespace std;int main(){ifstream in;int i, j, a[N][N];in.open("data.txt");if (!in){cout << "打开文件失败!" << endl;return -1;}for (i = 0; i < N; ++i){for (j = 0; j < N; ++j){if (in.eof())goto out;in >> a[i][j];cout << a[i][j] << '\t';}}out:cout << endl;in.close();return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP