Reputation: 307
How do I convert a string value into double format in C++?
Upvotes: 2
Views: 316
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
Reputation: 101456
Use stringstream
:
#include <sstream>
stringstream ss;
ss << "12.34";
double d = 0.0;
ss >> d;
Upvotes: 4
Reputation: 3413
If you're using the boost libraries, lexical cast is a very slick way of going about it.
Upvotes: 10