2

How do I convert a string value into double format in C++?

Cascabel
  • 479,068
  • 72
  • 370
  • 318
Beginner Pogrammer
  • 197
  • 2
  • 3
  • 12
  • possible duplicate of [How to parse a string to an int in C++?](http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c) – Björn Pollex Nov 14 '10 at 15:05

3 Answers3

10

If you're using the boost libraries, lexical cast is a very slick way of going about it.

Dave McClelland
  • 3,385
  • 1
  • 29
  • 44
4

Use stringstream :

#include <sstream>

stringstream ss;
ss << "12.34";
double d = 0.0;
ss >> d;
John Dibling
  • 99,718
  • 31
  • 186
  • 324
2

You can do with stringstream. You can also catch invalid inputs like giving non-digits and asking it to convert to int.

#include <iostream> 
#include <sstream>
using namespace std;

int main()
{
    stringstream s;
    string input;
    cout<<"Enter number: "<<endl;
    cin>>input;
    s.str(input);
    int i;
    if(s>>i)
        cout<<i<<endl;
    else
        cout<<"Invalid input: Couldn't convert to Int"<<endl;
}

If conversion fails, s>>i returns zero, hence it prints invalid input.

bjskishore123
  • 6,144
  • 9
  • 44
  • 66