C++ reads a two dimensional array method from an txt file

  • 2020-06-07 04:57:24
  • OfStack

This article is for taking notes,

Data from the 2-dimensional array 1500*2 saved in MATLAB is stored in the txt file in the following format:

MATLAB code:


fid=fopen('data.txt','wt');
for i=1:1500
  fprintf(fid,'%.3f\t%.3f\n',r(i,:));
end
fclose(fid);

r is a 1500*2 matrix

Read to the program in C++ using file flow:


#include<iostream>
#include<fstream>
#include<typeinfo>
using namespace std;
int main()
{
	float data[1500][2] = { 0 };// define 1 a 1500*2 The matrix used to store data 
	ifstream infile;// Defines a read file stream, as opposed to a program in
	infile.open("data.txt");// Open the file 
	for (int i = 0; i < 1500; i++)// Define a row loop 
	{
		for (int j = 0; j < 2; j++)// Define column loop 
		{
			infile >> data[i][j];// read 1 The values (Spaces, tabs, newlines) are written into the matrix, and the rows and columns are looped 
		}
	}
	infile.close();// Close the file after reading 
	cout << data[3][0] <<','<<data[3][1]<< endl;// The following code is used to verify that the values read are correct 
	cout << data[10][0] << ',' << data[10][1] << endl;
	cout << typeid(data[3][0]).name() << endl;
	cout << "Hello" << endl;
	system("pause");
	return 0;
}

Related articles: