Skip to content

Instantly share code, notes, and snippets.

@dasannikov
Created May 22, 2015 00:09
Show Gist options
  • Save dasannikov/62380c0c3c1fec16e666 to your computer and use it in GitHub Desktop.
Save dasannikov/62380c0c3c1fec16e666 to your computer and use it in GitHub Desktop.
CSV file reader
#ifndef _u_csv_h_
#define _u_csv_h_
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
class CSVRow {
public:
CSVRow(const std::string& fileName, const char separator = ',') :
separatorChar(separator),
file(fileName) {}
std::size_t size() const { return data.size(); }
// Use: while(row.nextRow()) { int a = row.asInt(0) }
std::istream& nextRow() { return readNextRow(file); }
// Type conversions
bool asBool(const int index) {
return (data[index][0] == 't' || data[index][0] == 'T');
}
int asInt(const int index) { return stoi(data[index]); }
float asFloat(const int index) { return stof(data[index]); }
double asDouble(const int index) { return stod(data[index]); }
std::string asString(const int index) { return data[index]; }
private:
std::istream& readNextRow(std::istream& str) {
std::string line;
do {
std::getline(str, line);
} while (line[0] == '#');
std::stringstream lineStream(line);
std::string cell;
data.clear();
while(std::getline(lineStream, cell, separatorChar)) {
data.push_back(cell);
}
return str;
}
const char separatorChar;
std::vector<std::string> data;
std::ifstream file;
};
#endif
/*
int main()
{
CSVRow row("test.csv", ';');
while(row.nextRow()) {
std::cout << row.asFloat(0) << " : " << row.asBool(1) << " : " << row.asString(2).length() << std::endl;
}
}
*/
@dasannikov
Copy link
Author

Line started with # in CSV file means comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment