473,804 Members | 3,156 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
14 8919
mlimber,

I tried compiling the same program with a later ver of MS C/C++
compiler, which is ...
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42
for 80x86

With this compiler the test program gives expected results. But the GCC
compiler that I am using is gcc version 3.3.1 (mingw special
20030804-1), and it still gives out garbage. And by the way I believe,
there is no garbage i/p in the test program and hence there is no
question of GIGO. Moreover, I don't think there is any need of
exception handling in the test code with the given valid input and I
don't understand how that extra piece of error checking will help. If
your compiler/lib gives you expected results with the given input, it
should behave the same without that as well.

Another simple test to confirm the problem is,

int main() { double d; cin >d; cout << d; return 0; }

Just enter the value 2.22507-308 after compiling with your compiler and
it should show the expected result. But if you try this with the GCC
compiler version that I have mentioned, it gives out garbage. This
piece of code behaves similar to the earlier test program with both the
compilers that I used.

Lastly I tried your changes with GCC and it generates exception and
that tells me that there is some definite issue in the related version
of c++ lib that it is using.

Regards,
Harish Sharma

Jul 29 '06 #11
sh**********@gm ail.com wrote:
if your compiler/lib gives you expected results with the given input, it
should behave the same without that as well.
I actually meant, if your compiler/lib gives you expected results with
the give input AND THE ERROR HANDLING CODE, it should behave the same
without that (error handling code) as well.

Regards,
Harish Sharma

Jul 29 '06 #12
sh**********@gm ail.com wrote:
mlimber,

I tried compiling the same program with a later ver of MS C/C++
compiler, which is ...
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42
for 80x86

With this compiler the test program gives expected results. But the GCC
compiler that I am using is gcc version 3.3.1 (mingw special
20030804-1), and it still gives out garbage. And by the way I believe,
there is no garbage i/p in the test program and hence there is no
question of GIGO.
I used g++ 3.4.4 (cygming special) to build and run this program:

#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdlib>

using namespace std;

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;
}

int main()
{
cout << "atof(2.225 07e-308) - "
<< atof("2.22507e-308") << '\n';
try
{
cout << "value<double>( 2.22507e-308) ->"
<< value<double>(" 2.22507e-308");
}
catch( ... )
{
cout << "Caught exception.";
}
cout << endl;
}

It gives me the expected result. If it does not for you, then it is
likely a compiler/library problem, which you should ask about on
gnu.g++.help or similar.
Moreover, I don't think there is any need of
exception handling in the test code with the given valid input and I
don't understand how that extra piece of error checking will help. If
your compiler/lib gives you expected results with the given input, it
should behave the same without that as well.

Lastly I tried your changes with GCC and it generates exception and
that tells me that there is some definite issue in the related version
of c++ lib that it is using.
The exception handling is an alternate way of handling unexpected
errors to checking return values (cf.
http://www.parashift.com/c++-faq-lit...html#faq-17.1). In
this case, exceptions provide a way to indicate a failure without
having some sort of potentially invalid value (e.g., return FLOAT_MIN
on error or a std::pair<float ,boolwhere the flag indicates validity)
being returned to the client, and the client can catch and handle such
an error at whatever level is appropriate. Anyway, the fact that you
get an exception seems to indicate that there was in fact an unexpected
error of some kind, so I think your claim that this sort of error
checking is unnecessary is self-defeating.

Cheers! --M

Jul 31 '06 #13
Anyway, the fact that you
get an exception seems to indicate that there was in fact an unexpected
error of some kind, so I think your claim that this sort of error
checking is unnecessary is self-defeating.
*self-defeating* ?

My comment on exception handling was not general and was specific to
the test code with the given *valid* input to the program.

Regards,
Harish Sharma

Aug 1 '06 #14
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.
atof() causes undefined behaviour if the result isn't representable
as a double. Change to strtod() instead of atof(), and see if you
still get the same problem.

Aug 1 '06 #15

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
15063
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
17797
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
3446
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
2334
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
8008
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
2135
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
9706
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
10575
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...
0
10330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10319
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
10076
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9144
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...
0
5520
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...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2990
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.