how to convert string to double?

K

kathy

I can not find something like atof() which can convert string to
double.

Can anyone help me?
 
X

xuatla

kathy said:
I can not find something like atof() which can convert string to
double.

Can anyone help me?

How about just using atof(s.c_str()), given s is a string in your case?

X
 
D

dakka

kathy said:
I can not find something like atof() which can convert string to
double.

Can anyone help me?

#include <iostream>
#include <sstream>

using namespace std;

double strtodouble(const string& what)
{
istringstream instr(what);
double val;
instr >> val;
return val;
}

int main()
{
string dbl("3.1415");
cout << strtodouble(dbl) << endl;
return 0;
}

--
--dakka

Dykstra's Observation:
If debugging is the process of removing bugs, then programming must be
the process of putting them in.
 
K

kathy

The following failed:

istringstream instr;
double val[2];
instr.str(str1);
instr >> val[0];
instr.str(str2);
instr >> val[2];

why?
 
M

mlimber

kathy said:
The following failed:

istringstream instr;
double val[2];
instr.str(str1);
instr >> val[0];

Because the stream state is currently set to fail, you need to clear
it:

instr.clear();
instr.str(str2);
instr >> val[1]; // Fixed as in your followup

why?

In the future, you should tell us how it failed. Fortunately, this one
was fairly easy to spot.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top