0

Possible Duplicate:
CSV parser in C++

Hello, I want to read a csv file into an 2D array in c++. Imagine my csv file is: a,b,c d,e,f Will someone help me to make of this a 2x3 table? Thanks,

Community
  • 1
  • 1
andre de boer
  • 3,124
  • 3
  • 17
  • 15
  • 3
    Have you seen this SO [question](http://stackoverflow.com/questions/1120140/csv-parser-in-c) ? – Nekresh Jan 12 '11 at 14:33
  • why not make an attempt to do this yourself? If your code does not work, and you cannot understand why not, then post your code and show how the results differ from what you expected. If you do this, people will give you help. – ravenspoint Jan 12 '11 at 14:40
  • Duplicate of the following question: http://stackoverflow.com/questions/1120140/csv-parser-in-c – Zamfir Kerlukson Feb 23 '13 at 10:03

1 Answers1

1

Oh alright here's something that'll do it. It's specialized to meet your needs but it works. I've also included a BOOST technique, but that's probably too advanced for you...

#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();
    }
}
Michael Smith
  • 403
  • 1
  • 3
  • 8