2

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

Cascabel
  • 451,903
  • 67
  • 363
  • 314
Beginner Pogrammer
  • 187
  • 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,325
  • 1
  • 27
  • 44
4

Use stringstream :

#include <sstream>

stringstream ss;
ss << "12.34";
double d = 0.0;
ss >> d;
John Dibling
  • 97,027
  • 28
  • 181
  • 313
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
  • 5,984
  • 9
  • 39
  • 65