From ba09cbae3e81be0df779215aa0ffa8acfb9dd81a Mon Sep 17 00:00:00 2001 From: Antonin Portelli Date: Sat, 30 Apr 2016 00:15:24 -0700 Subject: [PATCH] function to read std::vector from a string (blank separated values) --- lib/serialisation/BaseIO.h | 16 ++++++++++++++++ tests/Test_serialisation.cc | 14 ++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lib/serialisation/BaseIO.h b/lib/serialisation/BaseIO.h index b89d27ad..3c49692f 100644 --- a/lib/serialisation/BaseIO.h +++ b/lib/serialisation/BaseIO.h @@ -32,6 +32,22 @@ Author: Peter Boyle #include namespace Grid { + // helper function to read space-separated values + template + std::vector strToVec(const std::string s) + { + std::istringstream sstr(s); + T buf; + std::vector v; + + while(!sstr.eof()) + { + sstr >> buf; + v.push_back(buf); + } + + return v; + } class Serializable {}; diff --git a/tests/Test_serialisation.cc b/tests/Test_serialisation.cc index 22bb7025..42fdcccb 100644 --- a/tests/Test_serialisation.cc +++ b/tests/Test_serialisation.cc @@ -140,4 +140,18 @@ int main(int argc,char **argv) std::cout << "Loaded (txt) -----------------" << std::endl; std::cout << copy3 << std::endl << veccopy3 << std::endl; } + + std::vector iv = strToVec("1 2 2 4"); + std::vector sv = strToVec("bli bla blu"); + + for (auto &e: iv) + { + std::cout << e << " "; + } + std::cout << std::endl; + for (auto &e: sv) + { + std::cout << e << " "; + } + std::cout << std::endl; }