C++:导入txt中的矩阵

最近写C++代码的时候,需要把txt中保存的矩阵读入到C++定义的数组中,因此,本文记录了关键代码。


txt 文件中的矩阵

输入:

1 2 3 4 5 3 2
2 3 4 5 5 3 3
3 4 5 6 7 8 9
7 8 7 8 7 8 1

输出:
在这里插入图片描述


导入 txt 中的矩阵到 C++ 的二维矩阵中

#include <iostream>
#include <fstream>
#include<vector>
using namespace std;
#include <string> 


// ======== Funtion: getFileRows ===============================
// ========= output :矩阵行数 ===================================
// 逐行读取文件并计数,得到 txt 文件的行数
int getFileRows(const char* fileName) {
    ifstream fileStream;
    string tmp;
    int count = 0;// 行数计数器
    fileStream.open(fileName, ios::in);//ios::in 表示以只读的方式读取文件
    if (fileStream.fail())//文件打开失败:返回0
    {
        return 0;
    }
    else//文件存在
    {
        while (getline(fileStream, tmp, '\n'))//读取一行
        {
            if (tmp.size() > 0)
                count++;
        }
        fileStream.close();
        return count;
    }
}


// ======== Funtion: getFileColumns ============================
// ========= output :矩阵列数 ===================================
int getFileColumns(const char* fileName) {
    ifstream fileStream;
    fileStream.open(fileName, std::ios::_Nocreate);

    double tmp = 0;
    int count = 0;	// 列数计数器	
    char c;			//当前位置的字符
    c = fileStream.peek();
    while (('\n' != c) && (!fileStream.eof()))	// 指针指向的当前字符,仅观测,不移动指针位置
    {
        fileStream >> tmp;
        ++count;
        c = fileStream.peek();
    }

    fileStream.close();
    return count;
}


// ===========Funtion: getMatrix ===============================
// =========== output :二维矩阵 ==================================
double** getMatrix(const char* path, const int n, const int m) {
    fstream myfile;
    myfile.open(path); 

    double** mat = new double* [n];
    for (int i = 0; i < n; i++)
    {
        double* tmp = new double[m];
        mat[i] = tmp;
    }

    string tmpStr;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            myfile >> tmpStr;//
            double dValue = atof(tmpStr.c_str());
            mat[i][j] = dValue;
        }
    }
    return mat;
}


int main() {
    
    //txt文件保存路径
    const char* dataPath = "D:\\VisualStudioProjects\\ConsoleApplication1\\Test.txt";

    int n = getFileRows(dataPath);             //获取txt中的矩阵行数
    int m = getFileColumns(dataPath);          //获取txt中的矩阵列数
    double** mat = getMatrix(dataPath, n, m); //获取二维矩阵

    //打印矩阵到控制台
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << mat[i][j] << "\x20" ;
        }
        cout << endl;
    }

    return 0;
}

一维数组写入本地txt

#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

//int nSize = (int)x.size();

// 向txt文档中写入数据
ofstream dataFile;
dataFile.open("D:\\dataFile.txt", ofstream::app);
fstream file("D:\\dataFile.txt", ios::out);

for (int nIndex = 0; nIndex < nSize; nIndex++)
{
	dataFile << x[nIndex] << '\r' << endl;     // 写入数据
}
   
dataFile.close();                           // 关闭文档

读取csv中的数据

//	//读取方向约束
//	ifstream file;
//	file.open("E:\\W_ImplicitModeling\\W_TestData\\1.csv", std::ios_base::in);
//	std::vector<double> dxs;
//	std::vector<double> dys;
//	std::vector<double> dzs;
//	std::vector<double> vsx;
//	std::vector<double> vsy;
//	std::vector<double> vsz;
//	std::string s;
//	std::getline(file, s);
//	while (std::getline(file, s))
//	{
//		std::vector<std::string> datas = split(s, ',');
//		if (datas.size() < 4)
//			continue;
//		dxs.push_back(atof(datas[1].c_str()));
//		dys.push_back(atof(datas[2].c_str()));
//		dzs.push_back(atof(datas[3].c_str()));
//		vsx.push_back(atof(datas[6].c_str()));
//		vsy.push_back(atof(datas[7].c_str()));
//		vsz.push_back(atof(datas[8].c_str()));
//	}
//	file.close();

写入csv

//写入csv
	CStdioFile tempFile;
	CString strFile = _T("D:\\drill_hole_xyzp.csv");
	if (PathFileExists(strFile))
	{
		CFile::Remove(strFile);
	}
	tempFile.Open(strFile, CFile::modeCreate | CFile::modeReadWrite | CFile::typeText);
	tempFile.SeekToEnd();
	CString strDrillHoleXYZPTemp;
	CString strDrillHoleXYZP;
	for (int i = 0; i < nBoreholeVoxelCount; i++)
	{
		pX[i] = m_vecBoreholeStratumPointX[i];
		pY[i] = m_vecBoreholeStratumPointY[i];
		pZ[i] = m_vecBoreholeStratumPointZ[i];
		pV[i] = m_vecRockTypeIndex[i];
		strDrillHoleXYZPTemp.Format(_T("%f,%f,%f,%f\r"), pX[i], pY[i], pZ[i], pV[i]);
		strDrillHoleXYZP += strDrillHoleXYZPTemp;
	}
	tempFile.WriteString(strDrillHoleXYZP);
	tempFile.Flush();
	tempFile.Close();
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_养乐多_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值