O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.5. Parsing a String Containing a Number in Scientific Notation

Problem

You have a string containing a number in scientific notation, and you want to store the number’s value in a double variable.

Solution

The most direct way to parse a scientific notation number is by using the C++ library’s built-in stringstream class declared in <sstream>, as you can see in Example 3-7.

Example 3-7. Parsing a number in scientific notation

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

using namespace std;

double sciToDub(const string& str) {

   stringstream ss(str);
   double d = 0;
   ss >> d;

   if (ss.fail()) {
      string s = "Unable to format ";
      s += str;
      s += " as a number!";
      throw (s);
   }

   return (d);
}

int main() {

   try {
      cout << sciToDub("1.234e5") << endl;
      cout << sciToDub("6.02e-2") << endl;
      cout << sciToDub("asdf") << endl;
   }
   catch (string& e) {
      cerr << "Whoops: " << e << endl;
   }
}

Following is the output from this code:

123400
0.0602
Whoops: Unable to format asdf as a number!

Discussion

The stringstream class is, not surprisingly, a string that behaves like a stream. It is declared in <sstring>. If you need to parse a string that contains a number in scientific notation (see also Recipe 3.2), a stringstream will do the job nicely. The standard stream classes already “know” how to parse numbers, so don’t waste your time reimplementing this logic if you don’t have to.

In Example 3-7, I wrote the simple function sciToDub that takes a string parameter and returns the double it contains, if it is valid. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required