2023年12月2日发(作者:)

c语言如何读写.csv文件,如何在C中读取和解析CSV文件?如果你不关心转义逗号和换行符,并且你不能在引号中嵌入逗号和换行符(如果你不能逃脱…)那么它只有大约三行代码(OK 14 – >但是它只有15行读取整个文件)。std::vector<:string> getNextLineAndSplitIntoTokens(std::istream& str){std::vector<:string> result;std::string line;std::getline(str,line);std::stringstream lineStream(line);std::string cell;while(std::getline(lineStream,cell, ',')){_back(cell);}// This checks for a trailing comma with no data after (!lineStream && ()){// If there was a trailing comma then add an empty _back("");}return result;}我只是创建一个表示一行的类。然后流入该对象:#include#include#include#include#include#includeclass CSVRow{public:std::string const& operator[](std::size_t index) const{return m_data[index];}std::size_t size() const{return m_();}void readNextRow(std::istream& str){std::string line;std::getline(str, line);std::stringstream lineStream(line);std::string cell;m_();while(std::getline(lineStream, cell, ',')){m__back(cell);}// This checks for a trailing comma with no data after (!lineStream && ()){// If there was a trailing comma then add an empty element.m__back("");}}private:std::vector<:string> m_data;};std::istream& operator>>(std::istream& str, CSVRow& data){xtRow(str);return str;}int main(){std::ifstream file("");CSVRow row;while(file >> row){std::cout << "4th Element(" << row[3] << ")n";}}但是通过一些小的工作,我们可以在技术上创建一个迭代器:class CSVIterator{public:typedef std::input_iterator_tag iterator_category;typedef CSVRow value_type;typedef std::size_t difference_type;typedef CSVRow* pointer;typedef CSVRow& reference;CSVIterator(std::istream& str) :m_str(()?&str:NULL) { ++(*this); }CSVIterator() :m_str(NULL) {}// Pre IncrementCSVIterator& operator++() {if (m_str) { if (!((*m_str) >> m_row)){m_str = NULL;}}return *this;}// Post incrementCSVIterator operator++(int) {CSVIterator tmp(*this);++(*this);return tmp;}CSVRow const& operator*() const {return m_row;}CSVRow const* operator->() const {return &m_row;}bool operator==(CSVIterator const& rhs) {return ((this == &rhs) || ((this->m_str == NULL) && (rhs.m_str == NULL)));}bool operator!=(CSVIterator const& rhs) {return !((*this) == rhs);}private:std::istream* m_str;CSVRow m_row;};int main(){std::ifstream file("");for(CSVIterator loop(file); loop != CSVIterator(); ++loop){std::cout << "4th Element(" << (*loop)[3] << ")n";}}