如何高效从文本文件读取double类型数据并修正矩阵读取代码
问题描述
需要修改重载的operator>>函数,使其能正确读取文本文件中的double类型浮点数并存入DynamicMatrix对象。原代码通过单个字符读取int的方式无法处理带小数点的浮点数,同时原读取行列数的逻辑仅支持个位数,无法应对更大的矩阵规模。
文本文件格式说明:
- 首行是矩阵的行列数(用空格分隔)
- 后续行对应矩阵的每一行数据,每个数值用空格分隔
- 支持连续存储多个矩阵
原代码如下:
fstream& operator>>(fstream& file, DynamicMatrix& matrixIn) { string rowAndColLine; string dataline; char atofIsDumb[1] = { 0 }; getline(file, rowAndColLine); atofIsDumb[0] = rowAndColLine[0]; //Rows matrixIn.rows = atoi(atofIsDumb); atofIsDumb[0] = rowAndColLine[2]; //Cols matrixIn.cols = atoi(atofIsDumb); matrixIn.matrix = new double* [matrixIn.rows]; for (int i = 0; i < matrixIn.rows; i++) { matrixIn.matrix[i] = new double[matrixIn.cols]; for (int j = 0; j < matrixIn.cols; j++) { atofIsDumb[0] = dataline[j]; matrixIn.matrix[i][j] = atof(atofIsDumb); } } return file; }
示例文本文件内容:
4 2 1.35477 8.35009 9.68868 2.21034 3.08167 5.47221 1.88382 9.92881 2 3 9.96461 9.67695 7.25839 9.8111 1.09862 7.98106
修正方案
C++的fstream本身支持直接提取整数和浮点数,不需要手动处理单个字符。修正后的代码利用流的原生提取功能,既能正确读取浮点数,也能支持任意位数的行列数,同时兼容多矩阵连续读取的需求:
#include <sstream> // 需要包含该头文件 fstream& operator>>(fstream& file, DynamicMatrix& matrixIn) { // 读取行列数:流自动跳过空白字符,支持任意位数的数值 if (!(file >> matrixIn.rows >> matrixIn.cols)) { // 读取失败(如到文件末尾),直接返回 return file; } // 释放原有矩阵内存,避免泄漏 if (matrixIn.matrix != nullptr) { for (int i = 0; i < matrixIn.rows; i++) { delete[] matrixIn.matrix[i]; } delete[] matrixIn.matrix; } // 分配新的矩阵内存 matrixIn.matrix = new double*[matrixIn.rows]; for (int i = 0; i < matrixIn.rows; i++) { matrixIn.matrix[i] = new double[matrixIn.cols]; // 直接从流提取double数值,自动识别小数点格式 for (int j = 0; j < matrixIn.cols; j++) { file >> matrixIn.matrix[i][j]; } } return file; }
关键改动说明
- 行列数读取:用
file >> matrixIn.rows >> matrixIn.cols替代手动字符处理,流会自动跳过空格、换行等空白字符,支持任意位数的行列数。 - 浮点数读取:通过
file >> matrixIn.matrix[i][j]直接提取double类型,流会自动识别小数点、正负号等格式,完美处理浮点数。 - 内存安全:增加原有内存释放逻辑,避免重复分配导致的内存泄漏。
- 多矩阵兼容:流提取操作自动处理多个矩阵之间的换行和空格,只要文件格式符合要求,就能连续读取多个矩阵。
内容的提问来源于stack exchange,提问作者Makuta Arguilleres
相关产品推荐
相关产品推荐

