如何从文件中读取 100x24 矩阵并将其作为浮点矩阵保存在内存中?

How to read a 100x24 matrix from file and keep it in memory as a float matrix?

本文关键字:保存 内存 存在 文件 读取 100x24      更新时间:2023-10-16

这是我的代码,我可以将数据保存在字符矩阵中,但我想将其保存在浮点矩阵中

const unsigned int HEIGHT = 100;
const unsigned int WIDTH = 24 ;

char arr[HEIGHT][WIDTH];
ifstream fin;
fin.open("PW.txt");
string line;
//let's assume here the proper size of input Map
for (unsigned int i = 0; i < HEIGHT; i++)
{
getline(fin, line);
for (unsigned int j = 0; j < WIDTH; j++)
{
arr[i][j] = line[j];
}
}
//let's assume here the proper size of input Map
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
cout << arr[i][j]  ;
}
cout << endl;
}

如果你在互联网上搜索"c ++ read file matrix",你可能会看到这样的代码:

static const int MAX_ROWS = 100;
static const int MAX_COLUMNS = 24;
//...
double matrix[MAX_ROWS][MAX_COLUMNS];
double value = 0.0;
for (int row = 0; row < MAX_ROWS; ++row)
{
for (int column = 0; column < MAX_COLUMNS; ++column)
{
text_file >> value;
matrix[row][column] = value;
}
}

您可以通过将数据类型从double更改为float来读取float矩阵。