可能重复:
CSV parser in C++
您好, 我想在c ++中将csv文件读入2D数组。 想象一下我的csv文件是: A,B,C d,E,F 有人会帮我制作一张2x3的桌子吗? 谢谢,
答案 0 :(得分: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();
}
}