473,793 Members | 2,922 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

string to double conversion - atof() vs istringstream

I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<class T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}

Now for double type the lowest positive value is 2.22507-308 and I get
different answers when I use this function vs atof() function. I am not
getting the reason here. Interestingly, if I reduce the exponent value
from -308 to -307, I get similar results.

Regards,
Harry.

Jul 25 '06 #1
14 8918
Forgot to mention this before. atof() behaviour is expected for -308
exp and that of istringstream is wrong.

Regards,
Harry.

sh**********@gm ail.com wrote:
I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<class T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}

Now for double type the lowest positive value is 2.22507-308 and I get
different answers when I use this function vs atof() function. I am not
getting the reason here. Interestingly, if I reduce the exponent value
from -308 to -307, I get similar results.

Regards,
Harry.
Jul 25 '06 #2
sh**********@gm ail.com wrote:
I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<class T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}

Now for double type the lowest positive value is 2.22507-308 and I get
different answers when I use this function vs atof() function. I am not
getting the reason here. Interestingly, if I reduce the exponent value
from -308 to -307, I get similar results.
How different are the results? Floating point numbers are notoriously
tricky. See, e.g., these FAQs:

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

Cheers! --M

Jul 25 '06 #3
On 24 Jul 2006 20:12:21 -0700, sh**********@gm ail.com wrote:
>I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<cla ss T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}
You don't check any return or error value in that function. Moreover,
I would prefer an explicit stringToDoulble () function to a template.
>Now for double type the lowest positive value is 2.22507-308 and I get
different answers when I use this function vs atof() function. I am not
getting the reason here. Interestingly, if I reduce the exponent value
from -308 to -307, I get similar results.
Use strtod
(http://www.opengroup.org/onlinepubs/...ns/strtod.html)
and check endptr, errno and return value.

Best wishes,
Roland Pibinger
Jul 25 '06 #4
Roland,
stringToDouble( ) is definitely something that will resolve the issue,
but that is not I am looking for. I was interested in minimizing the
no. of specialized functions that I write. Moreover, I am using this
only for the intrinsic types. As for the error checking, I don't know
how I can add that with the template types without specializing it for
a certain type.

Regards,
Harish Sharma
Roland Pibinger wrote:
On 24 Jul 2006 20:12:21 -0700, sh**********@gm ail.com wrote:
I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<class T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}

You don't check any return or error value in that function. Moreover,
I would prefer an explicit stringToDoulble () function to a template.
Now for double type the lowest positive value is 2.22507-308 and I get
different answers when I use this function vs atof() function. I am not
getting the reason here. Interestingly, if I reduce the exponent value
from -308 to -307, I get similar results.

Use strtod
(http://www.opengroup.org/onlinepubs/...ns/strtod.html)
and check endptr, errno and return value.

Best wishes,
Roland Pibinger
Jul 26 '06 #5
mlimber,
The difference in the values is quite large to be neglected for a
rounding error as the faq says. And anyways I am not interested in
comparing any double type no.s here. The result that I get while using
this func is 2.64167e-308 while atof() returns 2.22507e-308. I
understand that atof() has minimal functionality and that too is type
specific, whereas the istringstream (or istream) has be generic.
However, I think the precision of default 6 digits is lost somewhere
while extracting the value from the string.

Regards,
Harish Sharma

mlimber wrote:
sh**********@gm ail.com wrote:
I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<class T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}

Now for double type the lowest positive value is 2.22507-308 and I get
different answers when I use this function vs atof() function. I am not
getting the reason here. Interestingly, if I reduce the exponent value
from -308 to -307, I get similar results.

How different are the results? Floating point numbers are notoriously
tricky. See, e.g., these FAQs:

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

Cheers! --M
Jul 26 '06 #6
sh**********@gm ail.com wrote:
Roland,
stringToDouble( ) is definitely something that will resolve the issue,

Please don't top-post. Your reply belongs following or interspersed
with properly trimmed quotes. See the newsgroup FAQ list:
<http://www.parashift.c om/c++-faq-lite/how-to-post.html#faq-5.4>


Brian
Jul 26 '06 #7
Roland Pibinger wrote:
On 24 Jul 2006 20:12:21 -0700, sh**********@gm ail.com wrote:
I need a conversion function that converts values from string to a
particular type. For this I have a template function that looks like
this ...

template<class T>
T value(const string& s)
{
istringstream(s );
T val;
is >val;
return val;
}

You don't check any return or error value in that function.
That is a good point. Are you sure the conversion didn't abort
prematurely? Please post a *complete* but *minimal* program (see FAQ
5.8) that demonstrates your problem so we can reproduce it.

Cheers! --M

Jul 26 '06 #8
#include <iostream>
#include <sstream>
#include <cstdlib>

using namespace std;

template<class T>
T value(string s)
{
istringstream(s );
T val; is >val;
return val;
}

int
main()
{
cout << "\natof(2.22507 e-308) ->" << atof("2.22507e-308");
cout << "\nvalue<double >(2.22507e-308) ->" <<
value<double>(" 2.22507e-308");
return 0;
}

Above is the complete demo program illustrating the problem. Actually
the value displayed by the template function is not consistent across
compilation and is sorta random (atleast I didn't see any pattern or
consistent values with every compilation). I checked the output with
MSVC as well as with GCC compiler. They give different values but
neither gives the right output.

Regards,
Harish Sharma

Jul 27 '06 #9
sh**********@gm ail.com wrote:
#include <iostream>
#include <sstream>
#include <cstdlib>

using namespace std;

template<class T>
T value(string s)
{
istringstream(s );
T val; is >val;
return val;
}
Try this instead:

class MyException {};

template<class T>
T value(const string& s)
{
istringstream is(s);
T val;
if( !(is >val) || !(is >ws).eof() )
{
throw MyException();
}
return val;
}

Or better, use boost::lexical_ cast, which does basically the same thing
'cept better. I get the same answer for both with the above code:

atof(2.22507e-308) ->2.22507e-308
value<double>(2 .22507e-308) ->2.22507e-308
>
int
main()
{
cout << "\natof(2.22507 e-308) ->" << atof("2.22507e-308");
cout << "\nvalue<double >(2.22507e-308) ->" <<
value<double>(" 2.22507e-308");
return 0;
}

Above is the complete demo program illustrating the problem. Actually
the value displayed by the template function is not consistent across
compilation and is sorta random (atleast I didn't see any pattern or
consistent values with every compilation). I checked the output with
MSVC as well as with GCC compiler. They give different values but
neither gives the right output.
That's probably because you forgot the variable name for the string
stream (it's using 's', which means you can't access the string that
was passed in and you have a global 'is' somewhere). GIGO.

Cheers! --M

Jul 27 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2230
by: Miki Tebeka | last post by:
Hello All, I'm shipping an application using py2exe. With Python2.3 it worked fine but when switching to Python2.4 I started getting "warning: string/unicode conversion" all over the place. Any ideas how to solve this (other than using 'filterwarnings')? Thanks.
1
2249
by: kaede | last post by:
Hi all, Given the following data format: { "(1,2), "(2.5, 3.5)", .... } I would like to define a vector<string> to stored this data: v = "(1,2)", v = "(2.5, 3.5"), .... and would like to extract the integer/double string value to real int/double and use it in computation. What is the best way to do it?
9
15062
by: el_boricua | last post by:
What is the best way to convert from a string to a int and from a string to double? I have a line that is tokenize and I need to parse to test the tokens and convert them to their respective values from string. Thanks, N
4
17796
by: Matt | last post by:
Hi there, I'm having a weird situation when converting strings to double. Normally, the following code would work right? double MyDouble = double.Parse("20.50"); // Error at runtime Well, it gives me an error at run time, telling me that the format of the input string is incorrect. Then, if i try with a comma instead of a dot, it works fine.
3
2305
by: Herb Stevenson | last post by:
Hello. I have a very large string reprentation of a number, for example "1000001002003004005006007008009010". If I user Double.Parse, I get something like 1.0000010020030041E+33 as my output. I need to do a mod 900 conversion on this long string value (i.e. loop thru the number consistently dividing by 900). The exponential notation seems to be causing some precision problems as I divide. Is there a way to have the double represnted...
2
3445
by: Bit Byte | last post by:
I want to parse a string (actually a date [always in the format 'YYYYMMDD') into integer values like this: void parseDate(const string&sdate, int& day, int& mon, int &year) { istringstream iss(sdate) ; .... } I can do this easily in C (using atoi etc), but i wanted not too sure
5
2333
oll3i
by: oll3i | last post by:
public class Cennik { private static Cennik instance = null; Map<String,Double> cennik = new HashMap<String,Double> (); private Cennik() { // prywatny konstruktor } public static Cennik getInstance() { if(instance == null) { instance = new Cennik();
1
8007
by: krishna81m | last post by:
I am a newbie and have been trying to understand conversion from double to int and then back to int using the following code was posted on the c++ google group. Could someone help me out with understanding why and how a double can be represented in bits and bytes and which of the following can allow us to view the binary representation, unsigned char representation and then convert back to int please... #include<iostream> #include<iomanip>...
5
2133
by: Evyn | last post by:
Hi all, I have recently asked for advice: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/1b42e6855a2c571b/e63d8f10b51f015c?lnk=raot#e63d8f10b51f015c My task is to convert a string of characters to a double. The string is read from a file and will be in the format 12345. The double output must be 0.12345. My answer to this problem was:
0
9671
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10433
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9035
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4112
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.