Beginner Pogrammer
Beginner Pogrammer

Reputation: 307

how to convert string value into double format in c++

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

Upvotes: 2

Views: 316

Answers (3)

bjskishore123
bjskishore123

Reputation: 6342

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.

Upvotes: 2

John Dibling
John Dibling

Reputation: 101456

Use stringstream :

#include <sstream>

stringstream ss;
ss << "12.34";
double d = 0.0;
ss >> d;

Upvotes: 4

Dave McClelland
Dave McClelland

Reputation: 3413

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

Upvotes: 10

Related Questions