C++ FAQ Celebrating Twenty-One Years of the C++ FAQ!!!
(Click here for a personal note from Marshall Cline.)
Section 39:
[39.2] How do I convert a std::string to a number?

There are two easy ways to do this: you can use the <cstdio> facilities or the <iostream> library. In general, you should prefer the <iostream> library.

The <iostream> library allows you to convert a std::string to pretty much anything using the following syntax (the example converts a double, but you could substitute pretty much anything that can be read using the >> operator):

// File: convert.h
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline double convertToDouble(std::string const& s)
{
  std::istringstream i(s);
  double x;
  if (!(i >> x))
    throw BadConversion("convertToDouble(\"" + s + "\")");
  return x;
}
The std::istringstream object i offers formatting facilities just like those for std::cin. You can use manipulators and format flags to control the formatting of the result, just as you can for other std::cin.

In this example, we initialize the std::istringstream i passing the std::string s (for example, s might be the string "123.456"), then we extract i into x via the overloaded extraction operator, >>. This invokes the iostream formatting facilities to convert as much of the string as possible/appropriate based on the type of x.

The if test makes sure the conversion works correctly. For example, if the string contains characters that are inappropriate for the type of x, the if test will fail.

Here's how to use the convertToDouble() function:

#include "convert.h"

void myCode()
{
  std::string s = ...a string representation of a number...;
  ...
  double x = convertToDouble(s);
  ...
}
You probably want to enhance convertToDouble() so it optionally checks that there aren't any left-over characters:
inline double convertToDouble(std::string const& s,
                              bool failIfLeftoverChars = true)
{
  std::istringstream i(s);
  double x;
  char c;
  if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
    throw BadConversion("convertToDouble(\"" + s + "\")");
  return x;
}