我是 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/