Connecting Tech Pros Worldwide Forums | Help | Site Map

how to convert string to double?

kathy
Guest
 
Posts: n/a
#1: Feb 8 '06
I can not find something like atof() which can convert string to
double.

Can anyone help me?


xuatla
Guest
 
Posts: n/a
#2: Feb 8 '06

re: how to convert string to double?


kathy wrote:[color=blue]
> I can not find something like atof() which can convert string to
> double.
>
> Can anyone help me?
>[/color]

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

X
Thomas Tutone
Guest
 
Posts: n/a
#3: Feb 9 '06

re: how to convert string to double?


kathy wrote:
[color=blue]
> I can not find something like atof() which can convert string to
> double.
>
> Can anyone help me?[/color]

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

dakka
Guest
 
Posts: n/a
#4: Feb 9 '06

re: how to convert string to double?


kathy wrote:[color=blue]
> I can not find something like atof() which can convert string to
> double.
>
> Can anyone help me?
>[/color]

#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.
kathy
Guest
 
Posts: n/a
#5: Feb 9 '06

re: how to convert string to double?


The following failed:

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

why?

kathy
Guest
 
Posts: n/a
#6: Feb 9 '06

re: how to convert string to double?


wrong typing:

instr >> val[2];

should be

instr >> val[1];

kathy
Guest
 
Posts: n/a
#7: Feb 9 '06

re: how to convert string to double?


wrong typing:

instr >> val[2];

should be

instr >> val[1];

mlimber
Guest
 
Posts: n/a
#8: Feb 9 '06

re: how to convert string to double?


kathy wrote:[color=blue]
> The following failed:
>
> istringstream instr;
> double val[2];
> instr.str(str1);
> instr >> val[0];[/color]

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

instr.clear();
[color=blue]
> instr.str(str2);
> instr >> val[1]; // Fixed as in your followup
>
> why?[/color]

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

Cheers! --M

kathy
Guest
 
Posts: n/a
#9: Feb 9 '06

re: how to convert string to double?


why it set to fail state?

Closed Thread