c++ - 使用 multimap 在 C++ 中读取和打印包含超过 2 列的 csv 文件

标签 c++ multimap

我是 c++ 的初学者,需要编写一个 c++ 程序来读取和打印这样的 csv 文件。

DateTime,value1,value2
12/07/16 13:00,3.60,50000
14/07/16 20:00,4.55,3000

我可以知道如何继续编程吗? 我设法仅通过简单的 multimap 代码获取日期。

最佳答案

我花了一些时间为您制定了几乎(阅读末尾的通知)精确的解决方案。

我假设您的程序是一个控制台应用程序,它接收原始 csv 文件名作为命令行参数。

因此请查看以下代码并根据需要进行必要的更改:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <string>

std::vector<std::string> getLineFromCSV(std::istream& str, std::map<int, int>& widthMap)
{
    std::vector<std::string> result;
    std::string line;
    std::getline(str, line);

    std::stringstream lineStream(line);
    std::string cell;

    int cellCnt = 0;

    while (std::getline(lineStream, cell, ','))
    {
        result.push_back(cell);
        int width = cell.length();
        if (width > widthMap[cellCnt])
            widthMap[cellCnt] = width;
        cellCnt++;
    }
    return result;
}

int main(int argc, char * argv[]) 
{
    std::vector<std::vector<std::string>> result; // table with data
    std::map<int, int> columnWidths; // map to store maximum length (value) of a string in the column (key)
    std::ifstream inpfile;
    // check file name in the argv[1]
    if (argc > 1)
    {
        inpfile.open(argv[1]);
        if (!inpfile.is_open())
        {
            std::cout << "File " << argv[1] << " cannot be read!" << std::endl;
            return 1;
        }
    }
    else
    {
        std::cout << "Run progran as: " << argv[0] << " input_file.csv" << std::endl;
        return 2;
    }
    // read from file stream line by line
    while (inpfile.good())
    {
        result.push_back(getLineFromCSV(inpfile, columnWidths));
    }
    // close the file
    inpfile.close();
    // output the results
    std::cout << "Content of the file:" << std::endl;
    for (std::vector<std::vector<std::string>>::iterator i = result.begin(); i != result.end(); i++)
    {
        int rawLen = i->size();
        for (int j = 0; j < rawLen; j++)
        {
            std::cout.width(columnWidths[j]);
            std::cout << (*i)[j] << " | ";
        }
        std::cout << std::endl;
    }
    return 0;
}

注意:您的任务只是将 vector 的 vector (用于 std::vector<std::vector<std::string>>result 类型)替换为 multimap (我希望您了解什么应该是您的关键解决方案)

关于c++ - 使用 multimap 在 C++ 中读取和打印包含超过 2 列的 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38627408/

相关文章:

c++ - 如何在autotools C++中添加boost单元测试框架

c++ - 无法编译代码 "launch: program <program_path> does not exist "

c++ - 等待句柄/事件异步或在同一线程内回调

c++ - 无法访问 multimap 迭代器的方法?

c++ - C++中矩阵的最小值

c++ - : "int i, (!!i)"?是什么意思

c++ - 对于测试非虚拟方法,模板或链接接缝依赖注入(inject)有哪些替代方案?

c++ - 交换 multimap<int, int> 中的每对值

Guava :迭代 Multimap 的键-> 集合条目的最佳方法?

dapper - Dapper 中的多重映射。在 SpiltOn 中收到错误