【问题标题】:read csv file into c++ [duplicate]将csv文件读入c ++ [重复]
【发布时间】:2011-06-07 21:11:06
【问题描述】:

可能重复:
CSV parser in C++

你好, 我想将 csv 文件读入 c++ 中的二维数组。 想象一下我的 csv 文件是: a,b,c d,e,f 有人会帮我把这个做成 2x3 的桌子吗? 谢谢,

【问题讨论】:

  • 你见过这个 SO question 吗?
  • 为什么不自己尝试一下呢?如果您的代码不起作用,并且您无法理解为什么不工作,请发布您的代码并显示结果与您的预期有何不同。如果你这样做,人们会给你帮助。

标签: c++


【解决方案1】:

哦,好吧,这是可以做到的。它专门满足您的需求,但它确实有效。我还包含了一个 BOOST 技术,但这对你来说可能太先进了......

#ifndef BOOST_METHOD
std::string popToken(std::string& text, const std::string& delimiter)
{
    std::string result = "";
    std::string::size_type pos = text.find(delimiter);
    if (pos != std::string::npos) {
        result.assign(text.begin(), text.begin() + pos);
        text.erase(text.begin(), text.begin() + pos + delimiter.length());        
    } else {
        text.swap(result);
    }
    return result;
}
#endif

void readCSV()
{
    const size_t rows = 2;
    const size_t cols = 3;
    std::string data[rows][cols];
    std::ifstream fin;

    fin.open("csv.txt");
    if (! fin.fail()) {
        std::string line;
        while (! fin.eof()) {
            fin >> line;
#ifdef BOOST_METHOD
            boost::tokenizer<boost::escaped_list_separator<char> > tknzr(line, boost::escaped_list_separator<char>('\\', ',', '\"'));
            boost::tokenizer<boost::escaped_list_separator<char> >::iterator it = tknzr.begin();
            for (size_t row = 0; row < rows && it != tknzr.end(); row++) {
                for (size_t col = 0; col < cols &&  it != tknzr.end(); col++, ++it) {
                    data[row][col] = *it;
                    std::cout << "(" << row << "," << col << ")" << data[row][col] << std::endl;
                }
            }
#else
            for (size_t row = 0; row < rows && line.length(); row++) {
                for (size_t col = 0; col < cols && line.length(); col++) {
                    data[row][col] = popToken(line, ",");
                    std::cout << "(" << row << "," << col << ")" << data[row][col] << std::endl;
                }
            }
#endif
        }
        fin.close();
    }
}

【讨论】:

  • 你可以自己弄清楚包含语句
  • 将#ifdef 直接放入代码中。哇。不是很好。真的很难阅读。
  • 是的。对于这个例子,无论如何......我什至回答了这是一个奇迹。
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 2023-04-09
  • 2017-05-01
  • 1970-01-01
  • 2023-03-30
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多