Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created November 13, 2013 01:54
Show Gist options
  • Save dgodfrey206/7442247 to your computer and use it in GitHub Desktop.
Save dgodfrey206/7442247 to your computer and use it in GitHub Desktop.
How to convert a string of doubles into a vector
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
template <class Facet>
struct erasable_facet : Facet
{
erasable_facet() : Facet(0) { }
~erasable_facet() { }
};
std::vector<double> convert(const std::string& str)
{
using num_get = std::num_get<char>;
erasable_facet<num_get> facet;
std::vector<double> v;
std::stringbuf buf(str);
std::ios ios(nullptr);
std::ios_base::iostate err = std::ios_base::goodbit;
double d;
std::istreambuf_iterator<char> it;
do
{
it = facet.get(&buf, std::istreambuf_iterator<char>(), ios, err, d);
buf.sbumpc();
v.push_back(d);
} while (it != std::istreambuf_iterator<char>());
return v;
}
int main()
{
std::string str = "1.24 5.32\n 9.53";
auto v = convert(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment