how would i go about converting a string to a double?
Printable View
how would i go about converting a string to a double?
1. Use the atof function:
2. Use stringstreams:Code:#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string str("19.874");
double d;
// Use atof to convert string to double
d = atof(str.c_str());
// Output double value
cout << d << endl;
return 0;
}
Code:#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str("19.874");
stringstream sstr(str);
double d;
// Extract double value from stringstream
sstr >> d;
// Output double value
cout << d << endl;
return 0;
}
http://www.cppreference.com/stdstring/atof.html
this is how you can do it in C not C++ hope it helps
[edit1]
took me a little while to find the correct link.
if you saw this with the old link, sorry to confuse you.
here is the index to the site with good details
http://www.cppreference.com/index.html
if all else fails google it.
[/edit1]
thanks for that...
also how do you convert a double to a string?
using <sstream>:
Code:#include <sstream>
using namespace std;
string makeString(double d)
{
ostringstream ss;
ss<<d<<flush;
return ss.str();
}
here is another link i found that might be of assistance to you.
all i did again was run a search on google to find it.
it uses stringstream to convert from and to the formats your looking for.
http://pegasus.rutgers.edu/~elflord/...ingstream.html