Use stringstream to parse a number : stringstream « File Stream « C++ Tutorial






#include <iostream>
#include <sstream>
#include <string>

using namespace std;

double parse(const string& str) {
  stringstream ss(str);
  double d = 0;
  ss >> d;
  if (ss.fail( )) {
    throw (str +" is not a number");
  }
  return (d);
}

int main( ) {
  try {
    cout << parse("1.234e5") << endl;
    cout << parse("6.02e-2") << endl;
    cout << parse("asdf") << endl;
  }
  catch (string& e) {
    cerr << e << endl;
  }
}
123400
0.0602
asdf is not a number








12.20.stringstream
12.20.1.Demonstrate string streams
12.20.2.Use stringstream to parse a number
12.20.3.stringstream::str( empty string): Empty the string
12.20.4.stringstream::str( ) returns a string