Last active
March 25, 2016 17:42
-
-
Save JamesBremner/64c464493f8fef9969b0 to your computer and use it in GitHub Desktop.
Parse CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example program | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <string> | |
#include <sstream> | |
void ParseCSV( | |
std::vector< std::string >& output, | |
const std::string& csv ) | |
{ | |
int q = 0; | |
int p = csv.find(","); | |
while( p != -1 ) | |
{ | |
output.push_back( csv.substr(q,p-q) ); | |
q = p+2; | |
p = csv.find(",",q); | |
} | |
// The terminating comma of the CSV is missing | |
// so we need to check if there is | |
// one more value to be appended | |
p = csv.find_last_of(","); | |
if( p != -1 ) | |
{ | |
output.push_back( csv.substr( p+2 ) ); | |
} | |
else | |
{ | |
// there was no comma | |
// this could be because the list is empty | |
// it could also be because there is just one element in the list | |
if( csv.length() > 1 ) | |
output.push_back( csv ); | |
} | |
} | |
void ParseCSV2( | |
std::vector< std::string >& output, | |
const std::string& csv ) | |
{ | |
std::stringstream sst(csv); | |
std::string a; | |
while( getline( sst, a, ',' ) ) | |
output.push_back(a); | |
} | |
int main() | |
{ | |
std::string test("this is my list, a, b, c, d, end of line"); | |
std::vector< std::string > split; | |
ParseCSV2( split, test ); | |
for( auto& s : split ) | |
std::cout << s << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment