Journal of computing related issues for Web Authoring, and general topics using Mac, Windows and Linux platforms.

Tuesday, July 3, 2007

C++ String to Double (strtod) function notes

As part of my ongoing exercise to write calculator in C++ I wanted to add capability of using memory content as parameter, e.g. add mem to current value.

Although I quickly determined that one solution was strtod function I had problems getting it to work until I read GID Forum at

I have cut and pasted relevent section here.

Garth Farley Garth Farley is offline
Invalid Email Address
Join Date: May 2002
Location: Ireland
Posts: 638
Garth Farley is a jewel in the roughGarth Farley is a jewel in the roughGarth Farley is a jewel in the rough
The problem is that strtod() is a function that has been around since the original C. C didn't have strings as we know it (a class which contains the characters), instead strings were character arrays, with the end being denoted by the a NULL terminator (\0).

So, in plain C, to get a string, you'd have

char[] word = {'h', 'e', 'l', 'l', 'o', '\0'};

These were pretty dodgy, since the only way to know the end of a string was to see the NULL character at the end. If the \0 is overwritten (and it can happen pretty easily), then the memory is continually read until a NULL character is found, getting a load of rubbish along the way. And writing to this would overwrite memory needed elsewhere, crashing all.

C++ improved this drastically, with the string class, which stores the length of the string along with a character array - so it doesn't rely on a NULL character.

However (getting back to the point), strtod() function only can accept C style strings, i.e. character arrays. You can convert a C++ string to a C string using a method of the string class, c_str().

word.c_str() - returns a character array with a NULL at the end.

So to answer your question, the syntax to get that working is:
CPP / C++ / C Code:
n1=strtod( t1.c_str() );

No comments:

About Me

Husband, dad and grandad. Physics graduate from London University in late 60s. Retired from IBM company in 2000 after 27 years as both Sytems Engineer and Salesman. Interests include photography, nature, science, maths, walking, travel. I like facts as a basis of opinion and not opinion that is assumed to be fact.