473,394 Members | 1,761 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

string to double

string strS;
stringstream stmT;
double dR;

stmT << strS;
stmT >> dR;

Is this the best way?

Jul 19 '05 #1
8 14833
Steven C. wrote:
string strS;
stringstream stmT;
double dR;

stmT << strS;
stmT >> dR;

Is this the best way?


No, you should test the stream state after reads and writes.
If you're going to do a lot of conversions from strings,

struct conversion_failure { };

template <typename T>
T from_string (const std::string & s)
{
T result;
std::istringstream stream (s);
if (stream >> result) return result;
throw conversion_failure ();
}

might come in handy. The client code becomes

double dR = from_string <double> (strS);

Regards,
Buster.

Jul 19 '05 #2
Thats not bad. I think this would be better though:

#include <sstream>
#include <string>
#include <ostream>

template <typename T>
bool fromString(const std::string &s, T &result)
{
std::istringstream stream ss;
return (stream >> result)
}

int main()
{
double d(0.0);
std::string s("34.543");

if (!fromString(s, d))
{
std::cerr << "error" << std::endl;
}
}

It doesnt need exceptions, and has greater type safety as you dont need
to specify the template type.

Buster Copley wrote:
Steven C. wrote:

struct conversion_failure { };

template <typename T>
T from_string (const std::string & s)
{
T result;
std::istringstream stream (s);
if (stream >> result) return result;
throw conversion_failure ();
}

might come in handy. The client code becomes

double dR = from_string <double> (strS);


Jul 19 '05 #3

Please don't top post - rearranged.

Ryan Winter <ry*********@optusnet.com.au> writes:
Buster Copley wrote:
Steven C. wrote:
struct conversion_failure { };
template <typename T>
T from_string (const std::string & s)
{
T result;
std::istringstream stream (s);
if (stream >> result) return result;
throw conversion_failure ();
}
might come in handy. The client code becomes
double dR = from_string <double> (strS);

Thats not bad. I think this would be better though:

#include <sstream>
#include <string>
#include <ostream>

template <typename T>
bool fromString(const std::string &s, T &result)
{
std::istringstream stream ss;
return (stream >> result)
}

int main()
{
double d(0.0);
std::string s("34.543");

if (!fromString(s, d))
{
std::cerr << "error" << std::endl;
}
}

It doesnt need exceptions, and has greater type safety as you dont
need to specify the template type.


The other solution doesn't "need" exceptions as well - BTW, writing
an error to stderr from a function designed to be put in a library
is not very sensible IMHO - what happens if you use it from a GUI
program?
Apart from that: the original solution is IMHO superior in that
you can do sth like

double d = fromString<double>(s);

whereas with your solution I'd be forced to write

double d;
fromString(s,d);

And why should you gain greater type safety if you can omit the
template type???

regards
frank

--
Frank Schmitt
4SC AG phone: +49 89 700763-0
e-mail: frankNO DOT SPAMschmitt AT 4sc DOT com
Jul 19 '05 #4
>>#include <sstream>
#include <string>
#include <ostream>

template <typename T>
bool fromString(const std::string &s, T &result)
{
std::istringstream stream ss;
return (stream >> result)
}

int main()
{
double d(0.0);
std::string s("34.543");

if (!fromString(s, d))
{
std::cerr << "error" << std::endl;
}
}

[snip]
The other solution doesn't "need" exceptions as well
Erm. Yes it does.
- BTW, writing
an error to stderr from a function designed to be put in a library
is not very sensible IMHO - what happens if you use it from a GUI
program?
This hypothetical library would contain 'fromString', not 'main'.
Apart from that: the original solution is IMHO superior in that
you can do sth like

double d = fromString<double>(s);
Thank you very much, but I don't agree.
whereas with your solution I'd be forced to write

double d;
fromString(s,d);
Careful now. You forgot the error checking:

if (fromString (s, d))
{
// non-exceptional code here
}
else
{
// other non-exceptional code. don't use d!
}
And why should you gain greater type safety if you can omit the
template type???


char c = from_string <int> ("1000000"); // oops

Regards,
Buster.

Jul 19 '05 #5
"Buster Copley" <bu****@none.com> wrote in message
news:bk**********@newsg2.svr.pol.co.uk...

No, you should test the stream state after reads and writes.
If you're going to do a lot of conversions from strings,
[snip]
double dR = from_string <double> (strS);

Regards,
Buster.


boost::lexical_cast can do stream conversions between any streamable types,
so one can go the other way too:

std::string strS = boost::lexical_cast<std::string>(dR);

In addition, compare
Jul 19 '05 #6
Buster Copley wrote:
#include <sstream>
#include <string>
#include <ostream>

template <typename T>
bool fromString(const std::string &s, T &result)
{
std::istringstream stream ss;
return (stream >> result)
}

int main()
{
double d(0.0);
std::string s("34.543");

if (!fromString(s, d))
{
std::cerr << "error" << std::endl;
}
}

[snip]
The other solution doesn't "need" exceptions as well

Erm. Yes it does.
- BTW, writing
an error to stderr from a function designed to be put in a library
is not very sensible IMHO - what happens if you use it from a GUI
program?

This hypothetical library would contain 'fromString', not 'main'.
Apart from that: the original solution is IMHO superior in that you
can do sth like

double d = fromString<double>(s);

Thank you very much, but I don't agree.
whereas with your solution I'd be forced to write

double d;
fromString(s,d);

Careful now. You forgot the error checking:

if (fromString (s, d))
{
// non-exceptional code here
}
else
{
// other non-exceptional code. don't use d!
}
And why should you gain greater type safety if you can omit the
template type???

char c = from_string <int> ("1000000"); // oops


You beat me to every single point Buster. Thanks :)

At least you got one thing right Frank, I should have followed the group
philosophy on top posting.

Ryan

Jul 19 '05 #7
Buster Copley <bu****@none.com> writes:
#include <sstream>
#include <string>
#include <ostream>

template <typename T>
bool fromString(const std::string &s, T &result)
{
std::istringstream stream ss;
return (stream >> result)
}

int main()
{
double d(0.0);
std::string s("34.543");

if (!fromString(s, d))
{
std::cerr << "error" << std::endl;
}
}
[snip]
The other solution doesn't "need" exceptions as well


Erm. Yes it does.
- BTW, writing
an error to stderr from a function designed to be put in a library
is not very sensible IMHO - what happens if you use it from a GUI
program?


This hypothetical library would contain 'fromString', not 'main'.


Ok, I missed that the std::cerr statement was in main and not in
fromString - sorry about that.
Apart from that: the original solution is IMHO superior in that you
can do sth like
double d = fromString<double>(s);


Thank you very much, but I don't agree.
whereas with your solution I'd be forced to write
double d;
fromString(s,d);


Careful now. You forgot the error checking:

if (fromString (s, d))
{
// non-exceptional code here
}
else
{
// other non-exceptional code. don't use d!
}


Thanks - this shows exactly why exceptions are preferable to error
codes. When using error codes, I have to clutter every function
in the call stack with error checking statements, whereas with
exceptions I can handle the error *once and for all* where I
want to.

regards
frank

--
Frank Schmitt
4SC AG phone: +49 89 700763-0
e-mail: frankNO DOT SPAMschmitt AT 4sc DOT com
Jul 19 '05 #8
Frank Schmitt wrote:
Buster Copley <bu****@none.com> writes:
if (fromString (s, d))
{
// non-exceptional code here
}
else
{
// other non-exceptional code. don't use d!
}

Thanks - this shows exactly why exceptions are preferable to error
codes. When using error codes, I have to clutter every function
in the call stack with error checking statements, whereas with
exceptions I can handle the error *once and for all* where I
want to.


Unless you want to react differently to different failures. In
that case, your code would be littered with try-catches instead.
It depends whether you see the condition you are testing for
as truly exceptional, or business as usual. It's your call.

Regards,
Buster.

Jul 19 '05 #9

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

Similar topics

4
by: cindy liu | last post by:
Hi, In .Net, how to convert a string to a double? Thanks in advance! Cindy
4
by: Venkat | last post by:
Hi All, I need to copy strings from a single dimensional array to a double dimensional array. Here is my program. #include <stdio.h> #include <stdlib.h>
7
by: hana1 | last post by:
Hello experts, I used to program in C/C++ and now switched to Java. I am having a difficulty that I need your help with. How can I limit a double variable to hold 2 decimal points only? Say I...
24
by: deko | last post by:
I'm trying to log error messages and sometimes (no telling when or where) the message contains a string with double quotes. Is there a way get the query to insert the string with the double...
2
by: flybird | last post by:
how can can I read the string( doubule characters:kanji or chinanese character ) from a text file using C#.
2
by: Carlos | last post by:
Hi all, just wanted to know how can I just quickly round to nearest 100th, and use the first two decimal places of a double value in a textbox, instead of all the decimals. Thanks in advance,...
84
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
5
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...
5
jeffbroodwar
by: jeffbroodwar | last post by:
Hi everyone, I have a program that converts variables long,string,double to byte array here's the code : for long : //CompanyId temp = longToByteArray(CompanyId); ...
7
by: JohnF | last post by:
I have a function textag($expression){...} whose $expression argument is a string that can contain substrings like \alpha with one backslash or like a&b\\c&d with two backslashes. If I write...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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...

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.