Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page