Skip to content

Instantly share code, notes, and snippets.

@Madsy
Created September 18, 2009 20:18
Show Gist options
  • Save Madsy/189273 to your computer and use it in GitHub Desktop.
Save Madsy/189273 to your computer and use it in GitHub Desktop.
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include <stdexcept>
/* Symptoms : std::istringstream::operator>> fails on the second run, while parsing "2.0"
Workaround: Recreate the istringstream object prior each call to operator>>, instead of resetting it with .str("")
But what causes this?
*/
int main()
{
using std::vector;
using std::string;
using std::istringstream;
using std::cout;
using std::endl;
try
{
vector<string> strbuf;
vector<float> fbuf;
istringstream sstrm;
strbuf.push_back(string("1.0"));
strbuf.push_back(string("2.0"));
strbuf.push_back(string("3.0"));
float f;
for(vector<string>::const_iterator it = strbuf.begin(); it != strbuf.end(); ++it)
{
string s = *it;
sstrm.str(s);
if(!(sstrm >> f)){
std::runtime_error re(string("Conversion failure while parsing string \"") + s + string("\"."));
throw re;
}
fbuf.push_back(f);
sstrm.str("");
}
for(vector<float>::const_iterator it = fbuf.begin(); it != fbuf.end(); ++it)
{
cout << *it << " ";
}
}
catch(std::bad_alloc& ba)
{
cout << "Out of memory." << endl;
}
catch(std::exception& e)
{
cout << "General exception: " << e.what() << endl;
}
catch(...)
{
cout << "Unknown exception." << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment