1. CSV-百度百科

2. 代码

#pragma once

//Microsoft Visual Studio 2015 Enterprise

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<cstdio>
#include<cstdlib>

using namespace std;

template<typename base_T>
class modifyCSVfile
{
private:
    struct arrInfo
    {
        double **arrName;
        int lineNum;
        int rowNum;
    };
public:
    string saveArray(base_T* arr, int lineNum, int rowNum, string fileName, int precis = 6);
    string saveArray(const vector<vector<base_T>>& arr, string fileName, int precis = 6);
    vector<vector<double>> CSVtoVector(string fileName);
    arrInfo CSVtoArray(string fileName);
    int delArray(arrInfo);
};

//*************************************************************************************************************************************************************
//*************************************************************************************************************************************************************
template<typename base_T>
string modifyCSVfile<base_T>::saveArray(base_T* arr, int lineNum, int rowNum, string fileName, int precis)
//函数功能:把一个int/float/double型二维数组,存入CSV文件
//参数1:数组第一个元素地址,e.g.【&array1[0][0]】;参数2:数组行数;参数3:数组列数;参数4:文件名;参数5:设置精度(默认精度是6)
{
    fileName += ".csv";    //保存成VSV格式文件,方便用Excel打开

                           //保存数组到文件。如果文件不存在,创建文件,并写入数据;如果文件存在,清空重新写入
    ofstream fout;
    fout.open(fileName.c_str(), ios_base::trunc);
    fout << showpoint;
    fout.precision(precis);
    for (int i = 0; i < lineNum; i++)
    {
        for (int j = 0; j < rowNum; j++)
        {
            if (j < rowNum - 1)
                fout << *(arr + i * rowNum + j) << ",";        // arr + i * rowNum + j:找到当前数组元素的顺序索引值
            else
                fout << *(arr + i * rowNum + j) << endl;
        }
    }
    fout.close();
    return fileName;
}

////用法示例:Visual Studio 2017 Community
//#include<iostream>
//#include<fstream>
//#include<string>
//#include<vector>
//#include"modifyCSVfile.h"
//
//const int arr_lineNum = 5;
//const int arr_rowNum = 7;
//int main()
//{
//    //定义一个double型二维数组,并赋值
//    double k = 1.1;
//    double arr[arr_lineNum][arr_rowNum];
//    for (int i = 0; i < arr_lineNum; i++)
//    {
//        for (int j = 0; j < arr_rowNum; j++)
//        {
//            arr[i][j] = k;
//            k = k + 1;
//        }
//    }
//
//    //输出当前数组到屏幕
//    for (int i = 0; i < arr_lineNum; i++)
//    {
//        for (int j = 0; j < arr_rowNum; j++)
//        {
//            cout << arr[i][j] << " ";
//        }
//        cout << endl;
//    }
//    system("pause");
//
//    //把当前数组存如文件。文件位置:当前工程文件夹下。文件格式为.csv,可用文本文档打开,也可用Excel打开。
//    modifyCSVfile<double> save;
//    save.saveArray(&arr[0][0], arr_lineNum, arr_rowNum, "arr1", 6);
//
//    return 0;
//}

//*************************************************************************************************************************************************************
//*************************************************************************************************************************************************************
template<typename base_T>
string modifyCSVfile<base_T>::saveArray(const vector<vector<base_T>>& arr, string fileName, int precis)
//函数功能:把一个vector二维数组,存入CSV文件
//参数1:vector对象名;参数2:文件名;参数3:设置精度(默认精度是6)
{
    fileName += ".csv";    //保存成VSV格式文件,方便用Excel打开

                           //保存数组到文件。如果文件不存在,创建文件,并写入数据;如果文件存在,清空重新写入
    ofstream fout;
    fout.open(fileName.c_str(), ios_base::trunc);
    fout << showpoint;
    fout.precision(precis);
    for (unsigned int i = 0; i < arr.size(); i++)
    {
        for (unsigned int j = 0; j < arr[i].size(); j++)
        {
            if (j <  arr[i].size() - 1)
                fout << arr[i][j] << ",";
            else
                fout << arr[i][j] << endl;
        }
    }
    fout.close();
    return fileName;
}

////用法示例:Visual Studio 2017 Community
//#include<iostream>
//#include<fstream>
//#include<string>
//#include<vector>
//#include"modifyCSVfile.h"
//
//int main()
//{
//    //定义一个二维vector数组,并赋值
//    double k = 1.1;
//    int lineNum = 5, rowNum = 7;
//    vector<vector<double> > arr2(lineNum, vector<double>(rowNum));
//    for (int i = 0; i < lineNum; i++)
//    {
//        for (int j = 0; j < rowNum; j++)
//        {
//            arr2[i][j] = k;
//            k = k + 1;
//        }
//    }
//
//    //输出当前数组到屏幕
//    for (int i = 0; i < lineNum; i++)
//    {
//        for (int j = 0; j < rowNum; j++)
//            cout << arr2[i][j] << " ";
//        cout << endl;
//    }
//    system("pause");
//
//    //把当前数组存如文件。文件位置:当前工程文件夹下。文件格式为.csv,可用文本文档打开,也可用Excel打开。
//    modifyCSVfile<double> save;
//    save.saveArray(arr2, "arr2", 6);
//
//    return    0;
//}

//*************************************************************************************************************************************************************
//*************************************************************************************************************************************************************
template<typename base_T>
vector<vector<double>> modifyCSVfile<base_T>::CSVtoVector(string fileName)
//函数功能:读取只包含数据不包含文字的CSV文件,并取出里边的数据存入到二维double型vector数组中
//参数1:文件名
{
    fileName += ".csv";
    ifstream fin;
    fin.open(fileName.c_str(), ios_base::in);        //以只读的方式打开文件

                                                     //跳过CSV文件开头可能出现的空行
    char ch;
    while (fin.get(ch))
    {
        if (ch == '\n')
            continue;
        else
            break;
    }
    streamoff pos = fin.tellg();            //保存当前位置
    fin.seekg(pos - 1, ios_base::beg);        //返回到文件中有数据开始的那一行的首位

                                              //获取CSV文件中数据的行数
    int lineNum = 0, rowNum = 0;
    string buf;
    while (getline(fin, buf) && !buf.empty())
    {
        lineNum = lineNum + 1;
    }
    fin.clear();        //getline()读取到文件尾,接下来输入流被阻断。需要重置输入流,如果不重置,接下来将无法获取文件数据。

                        //获取CSV文件中数据的列数
    fin.seekg(pos - 1, ios_base::beg);        //返回到文件中有数据开始的那一行的首位
    while (fin.get(ch))
    {
        if (ch == ',')
        {
            rowNum = rowNum + 1;
        }
        else
            if (ch == '\n')
                break;
    }
    rowNum = rowNum + 1;

    //把CSV文件中的数据存入double型的vector中
    fin.seekg(pos - 1, ios_base::beg);        //返回到文件中有数据开始的那一行的首位
    buf.erase(0);
    double temp;
    vector<vector<double>>vect(lineNum, vector<double>(rowNum));
    for (int i = 0; i < lineNum; i++)
    {
        for (int j = 0; j < rowNum; j++)
        {
            while (fin.get(ch))
            {
                if (ch != ',' && ch != '\n')
                    buf += ch;
                else
                {
                    temp = atof(buf.c_str());
                    vect[i][j] = temp;
                    buf.erase(0);
                    break;
                }
            }
        }
    }
    fin.close();

    return vect;
}

////用法示例:Visual Studio 2017 Community
//#include<iostream>
//#include<fstream>
//#include<string>
//#include<vector>
//#include<cstdio>
//#include<cstdlib>
//#include"modifyCSVfile.h"
//
//using namespace std;
//
//int main()
//{
//
//    vector<vector<double>> arr1;        //创建一个二维vector数组,用于接受函数调用返回的二维vector数组
//    modifyCSVfile<double> read;
//    arr1 = read.CSVtoVector("arr2");
//
//    //输出arr1到屏幕
//    for (int i = 0; i < 4; i++)
//    {
//        for (int j = 0; j < 4; j++)
//        {
//            cout << arr1[i][j] << " ";
//        }
//        cout << endl;
//    }
//
//    system("pause");
//    return    0;
//}

//*************************************************************************************************************************************************************
//*************************************************************************************************************************************************************
template<typename base_T>
typename modifyCSVfile<base_T>::arrInfo modifyCSVfile<base_T>::CSVtoArray(string fileName)
//函数功能:读取只包含数据不包含文字的CSV文件,并取出里边的数据存入到new创建的动态二维数组中
//参数1:文件名
{
    fileName += ".csv";
    ifstream fin;
    fin.open(fileName.c_str(), ios_base::in);        //以只读的方式打开文件

                                                     //跳过CSV文件开头可能出现的空行
    char ch;
    while (fin.get(ch))
    {
        if (ch == '\n')
            continue;
        else
            break;
    }
    streamoff pos = fin.tellg();            //保存当前位置
    fin.seekg(pos - 1, ios_base::beg);        //返回到文件中有数据开始的那一行的首位

                                              //获取CSV文件中数据的行数
    int lineNum = 0, rowNum = 0;
    string buf;
    while (getline(fin, buf) && !buf.empty())
    {
        lineNum = lineNum + 1;
    }
    fin.clear();        //getline()读取到文件尾,接下来输入流被阻断。需要重置输入流,如果不重置,接下来将无法获取文件数据。

                        //获取CSV文件中数据的列数
    fin.seekg(pos - 1, ios_base::beg);        //返回到文件中有数据开始的那一行的首位
    while (fin.get(ch))
    {
        if (ch == ',')
        {
            rowNum = rowNum + 1;
        }
        else
            if (ch == '\n')
                break;
    }
    rowNum = rowNum + 1;

    //new创建二维动态数组
    double **arr = new double *[lineNum];
    for (int i = 0; i < lineNum; i++)
    {
        arr[i] = new double[rowNum];
    }

    //把CSV文件中的数据存入二维数组中
    fin.seekg(pos - 1, ios_base::beg);        //返回到文件中有数据开始的那一行的首位
    buf.erase(0);
    double temp;
    for (int i = 0; i < lineNum; i++)
    {
        for (int j = 0; j < rowNum; j++)
        {
            while (fin.get(ch))
            {
                if (ch != ',' && ch != '\n')
                    buf += ch;
                else
                {
                    temp = atof(buf.c_str());
                    arr[i][j] = temp;
                    buf.erase(0);
                    break;
                }
            }
        }
    }
    fin.close();

    //创建一个结构对象,保存:指向当前数组的指针、当前数组行数、当前数组列数
    arrInfo info;
    info.arrName = arr;
    info.lineNum = lineNum;
    info.rowNum = rowNum;

    return info;        //返回结构
}

////用法示例:Visual Studio 2017 Community
//#include<iostream>
//#include<fstream>
//#include<string>
//#include<vector>
//#include<cstdio>
//#include<cstdlib>
//#include"modifyCSVfile.h"
//
//using namespace std;
//
//int main()
//{
//    //读取CSV文件arr2中的数据,返回一个结构。结构包括:指向数组的指针、数组行数、数组列数
//    modifyCSVfile<double> read;
//    auto arr1 = read.CSVtoArray("arr2");
//
//    //输出数组数据到屏幕
//    for (int i = 0; i < arr1.lineNum; i++)
//    {
//        for (int j = 0; j < arr1.rowNum; j++)
//        {
//            cout << arr1.arrName[i][j] << " ";
//        }
//        cout << endl;
//    }
//
//    //注意:由于调用CSVtoArray函数时,生成的数组是用new分配的,所以数据用完之后要记得释放。
//    //这里没有释放,可以调用delArray函数释放。
//
//    system("pause");
//    return    0;
//}

//*************************************************************************************************************************************************************
//*************************************************************************************************************************************************************
template<typename base_T>
int modifyCSVfile<base_T>::delArray(arrInfo info)
//函数功能:删除调用CSVtoArray函数时生成的动态二维数组
//由于CSVtoArray函数里边的二维数组是使用new创建的,所以用完之后要释放
{
    for (int i = 0; i < info.lineNum; i++)
        delete[] info.arrName[i];
    delete[] info.arrName;

    return 0;
}

////用法示例:Visual Studio 2017 Community
//#include<iostream>
//#include<fstream>
//#include<string>
//#include<vector>
//#include<cstdio>
//#include<cstdlib>
//#include"modifyCSVfile.h"
//
//using namespace std;
//
//int main()
//{
//    //读取CSV文件arr2中的数据,返回一个结构。结构包括:指向数组的指针、数组行数、数组列数
//    modifyCSVfile<double> read;
//    auto arr1 = read.CSVtoArray("arr2");
//
//    //输出数组数据到屏幕
//    for (int i = 0; i < arr1.lineNum; i++)
//    {
//        for (int j = 0; j < arr1.rowNum; j++)
//        {
//            cout << arr1.arrName[i][j] << " ";
//        }
//        cout << endl;
//    }
//
//    //释放调用CSVtoArray函数时用new生成的动态二维数组
//    modifyCSVfile<double> del;
//    del.delArray(arr1);
//
//    system("pause");
//    return    0;
//}


未完 ......

点击访问原文(进入后根据右侧标签,快速定位到本文)

C++ 把数组数据存入 CSV 文件,以及读取 CSV 文件的数据的更多相关文章

  1. 从文件中读取yuv和h264数据

    1.从文件中读取h264数据 参考ffmpeg avc.c写的从文件中一帧帧读取h.264数据的demo #include <stdio.h> #include <stdlib.h& ...

  2. spring 框架的xml文件如何读取properties文件数据

    spring 框架的xml文件如何读取properties文件数据 第一步:在spring配置文件中 注意:value可以多配置几个properties文件 <bean id="pro ...

  3. c文件二进制读取写入文件、c语言实现二进制(01)转化成txt格式文本、c读取文件名可变

    c语言实现二进制(01)转化成txt格式文本: 下面的程序只能实现ascall对应字符转换,如果文件内出现中文字符,则会出现错误. 本程序要自己创建个文本格式的输入文件a1.txt,编译后能将文本文件 ...

  4. java读取 500M 以上文件,java读取大文件

    java 读取txt,java读取大文件 设置缓存大小BUFFER_SIZE ,Config.tempdatafile是文件地址 来源博客http://yijianfengvip.blog.163.c ...

  5. 通过文件路径读取CSV表格内的数据

    ReadDataFromCSV.h UCLASS() class MYPROJECT_API UReadDataFromCSV : public UBlueprintFunctionLibrary { ...

  6. C#写入(覆盖形式)数据到CSV文件 和 读取CSV文件

    /// <summary> /// 写入数据到CSV文件,覆盖形式 /// </summary> /// <param name="csvPath"& ...

  7. php操作文件(读取写入文件)

    一,PHP如何读取文件 PHP读取文件可以读取当前服务器或远程服务器中的文件.其步骤是:打开文件.读文件和关闭文件. 1,PHP如何打开文件 使用PHP函数fopen()打开一个文件,fopen()一 ...

  8. Node.js——fs模块(文件系统),创建、删除目录(文件),读取写入文件流

    /* 1. fs.stat 检测是文件还是目录(目录 文件是否存在) 2. fs.mkdir 创建目录 (创建之前先判断是否存在) 3. fs.writeFile 写入文件(文件不存在就创建,但不能创 ...

  9. [Python] python3 文件操作:从键盘输入、打开关闭文件、读取写入文件、重命名与删除文件等

    1.从键盘输入 Python 2有两个内置的函数用于从标准输入读取数据,默认情况下来自键盘.这两个函数分别是:input()和raw_input(). Python 3中,不建议使用raw_input ...

  10. 在JavaScript文件中读取properties文件的方法

    假设有JavaScript文件叫做:readproperties.js,这个文件需要读取config.properties这个配置文件,步骤如下: 1.  下载插件jquery.i18n.proper ...

随机推荐

  1. learning java FileVisitor 遍丽文件及路径

    import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttribut ...

  2. “知乎杯”2018 CCF 大学生计算机系统与程序设计竞赛 贪心算法(greedy)

    --> 贪心算法 1)题解 •        分别用V0.V1和V>=2表示度为0.1以及至少为2的顶点集合 •        对于每个顶点,维护三个属性: •        degree ...

  3. “知乎杯”2018 CCF 大学生计算机系统与程序设计竞赛 绝地求生(battleground)

    /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-ts ...

  4. luoguP3003 [USACO10DEC]苹果交货Apple Delivery

    LOL新英雄卡莎点击就送 一句话题意: 三个点a1,a2,b,求从b到a1和a2的最短路 做法:求出a1->b和a2->b的最短路,两者取min,之后再加上a1->a2的最短路 为啥 ...

  5. JavaScript中字符串多行编辑

    常用写法: var str = 'w3c' +'标准' +'方式.' 升级版:var str = ['w3c','标准','方式.'].join('');终极版:var str = 'w3c\标准\方 ...

  6. 从Word到Latex文档

    有时,从Word文档复制到Latex文档时会编译报错,这时要检查某些特殊字符.中文输入法下的字符有时无法正确编译,要用相应的英文输入法下的字符替代.拉丁字母.希腊字母应该用转义字符实现.

  7. JDK 下载相关资料

    所有版本JDK下载地址: http://www.oracle.com/technetwork/java/archive-139210.html 下载账户密码: 2696671285@qq.com Or ...

  8. mysql 数据插入insert

    mysql> select * from user; +------+----------+-----------+ | id | name | address | +------+------ ...

  9. firewalld添加/删除服务service,端口port

    启动CentOS/RHEL 7后,防火墙规则设置由firewalld服务进程默认管理. 一个叫做firewall-cmd的命令行客户端支持和这个守护进程通信以永久修改防火墙规则. # firewall ...

  10. 第07组 Alpha冲刺(5/6)

    队名:摇光 队长:杨明哲 组长博客:求戳 作业博客:求再戳 队长:杨明哲 过去两天完成了哪些任务 文字/口头描述:依然在完善网页编辑器的后端. 展示GitHub当日代码/文档签入记录:(组内共用,已询 ...