C++ Converting a String to Double
Solution 1
#include <sstream>
int main(int argc, char *argv[])
{
double f = 0.0;
std::stringstream ss;
std::string s = "3.1415";
ss << s;
ss >> f;
cout << f;
}
The good thing is, that this solution works for others also, like ints, etc.
If you want to repeatedly use the same buffer, you must do ss.clear
in between.
There is also a shorter solution available where you can initialize the value to a stringstream and flush it to a double at the same time:
#include <sstream>
int main(int argc, char *argv[]){
stringstream("3.1415")>>f ;
}
Solution 2
Since C++11 you could use std::stod
function:
string line;
double lineconverted;
try
{
lineconverted = std::stod(line);
}
catch(std::invalid_argument)
{
// can't convert
}
But solution with std::stringstream
also correct:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
std::string str;
std::cin >> str;
std::istringstream iss(str);
double d = 0;
iss >> d;
std::cout << d << std::endl;
return 0;
}
PewK
Updated on March 04, 2020Comments
-
PewK about 4 years
I've been trying to find the solution for this all day! You might label this as re-post but what I'm really looking for is a solution without using boost lexical cast. A traditional C++ way of doing it would be great. I tried this code but it returns a set of gibberish numbers and letters.
string line; double lineconverted; istringstream buffer(line); lineconverted; buffer >> lineconverted;
And I alse tried this, but it ALWAYS returns 0.
stringstream convert(line); if ( !(convert >> lineconverted) ) { lineconverted = 0; }
Thanks in advance :)
EDIT: For the first solution I used (gibberish).. Here's a snapshot
-
awesoon almost 11 yearsAre you sure, that you have C++11 enabled?
-
PewK almost 11 yearsI'm new to C++, enlighten me 'how to' please :)
-
awesoon almost 11 years@PJ_Boy: Are you using MSVS? What version?
-
awesoon almost 11 years@PJ_Boy, nice. Read this, it could helps you.
-
Ed Abucay almost 11 yearsthat uses a gcc compiler try to get it's version -- and search if it supports C++11 (c++0x).
-
Celeritas over 9 yearsYour catch statment is invalid
-
awesoon over 9 yearsCould you clarify that, please?