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,
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,
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();
}
}