Last active
March 16, 2024 03:00
-
-
Save danilolc/1dedb7d165fccdd7a7c127f698fbf9c3 to your computer and use it in GitHub Desktop.
Function to transform a CSV line into C++ variables.
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
// Danilo Lemos - 2021 | |
// cool_csv.cpp | |
// ====================== | |
// A small and free to use/edit function to read a CSV line. | |
#include <string> | |
#include <sstream> | |
#include <iostream> | |
void Cool_CSV(const std::string &line) {} | |
template <typename... Args, typename T> | |
void Cool_CSV(const std::string &line, T &arg1, Args &...args) | |
{ | |
std::size_t comma = line.find(','); | |
std::string value = line.substr(0, comma); | |
std::istringstream iss(value); | |
iss >> arg1; | |
if (comma != std::string::npos) | |
Cool_CSV(line.substr(comma + 1), args...); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// Our CSV line contains two ints, one string and two floats. | |
int a, b; | |
std::string c; | |
float d, e; | |
// Pass the line and the variables that will receive the values | |
Cool_CSV("36, 41, Teste, 52.1, 213.1", a, b, c, d, e); | |
// Show the values that have been read from the line | |
std::cout << a << ", " << b << ", " << c << ", " << d << ", " << e << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment