472,145 Members | 1,625 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,145 software developers and data experts.

how to convert string to double?

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

Can anyone help me?

Feb 8 '06 #1
8 41551
kathy wrote:
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
Feb 8 '06 #2
kathy wrote:
I can not find something like atof() which can convert string to
double.

Can anyone help me?


It's in the FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-39.2

You may want to read the rest of the FAQ too - I bet you'll find it
very helpful.

Best regards,

Tom

Feb 9 '06 #3
kathy wrote:
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.
Feb 9 '06 #4
The following failed:

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

why?

Feb 9 '06 #5
wrong typing:

instr >> val[2];

should be

instr >> val[1];

Feb 9 '06 #6
wrong typing:

instr >> val[2];

should be

instr >> val[1];

Feb 9 '06 #7
kathy wrote:
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

Feb 9 '06 #8
why it set to fail state?

Feb 9 '06 #9

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by cindy liu | last post: by
3 posts views Thread by Norvin Laudon | last post: by
17 posts views Thread by David Scemama | last post: by
1 post views Thread by joe | last post: by
12 posts views Thread by Peter | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.