473,756 Members | 8,132 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

string to double

string strS;
stringstream stmT;
double dR;

stmT << strS;
stmT >> dR;

Is this the best way?

Jul 19 '05 #1
8 14848
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_fail ure { };

template <typename T>
T from_string (const std::string & s)
{
T result;
std::istringstr eam stream (s);
if (stream >> result) return result;
throw conversion_fail ure ();
}

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(cons t std::string &s, T &result)
{
std::istringstr eam 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_fail ure { };

template <typename T>
T from_string (const std::string & s)
{
T result;
std::istringstr eam stream (s);
if (stream >> result) return result;
throw conversion_fail ure ();
}

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*********@op tusnet.com.au> writes:
Buster Copley wrote:
Steven C. wrote:
struct conversion_fail ure { };
template <typename T>
T from_string (const std::string & s)
{
T result;
std::istringstr eam stream (s);
if (stream >> result) return result;
throw conversion_fail ure ();
}
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(cons t std::string &s, T &result)
{
std::istringstr eam 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<doub le>(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(cons t std::string &s, T &result)
{
std::istringstr eam 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<doub le>(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.co m> wrote in message
news:bk******** **@newsg2.svr.p ol.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::strin g>(dR);

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

template <typename T>
bool fromString(cons t std::string &s, T &result)
{
std::istringstr eam 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<doub le>(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.co m> writes:
#include <sstream>
#include <string>
#include <ostream>

template <typename T>
bool fromString(cons t std::string &s, T &result)
{
std::istringstr eam 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<doub le>(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.co m> 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
47070
by: cindy liu | last post by:
Hi, In .Net, how to convert a string to a double? Thanks in advance! Cindy
4
2781
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
43171
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 have an array of 50 doubles that each ahs a number such as 23.9918444. I want to round round this number to 23.99 and any other calculations done on it should have the same precision. I know that Decimal Format does the rounding but the thing that...
24
22647
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 quotes? Do I need to use code to scrub each string and remove or escape the double quotes before using it in a query? The error I get is this: Error Number 3075: Syntax error (missing operator) in query expression '"credit card billed by...
2
1370
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
2879
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, Carlos
84
15890
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
2327
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();
5
16145
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); for (i=0,i2=7; i<5; i++,i2--)
7
13044
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 <?php textag('\alpha'); ?with the expression argument in single quotes, then that works fine, and the single backslash isn't interpreted or changed, which is what I want. But if I write <?php textag('a&b\\c&d'); ?>
0
9456
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
9275
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
10040
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
9873
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...
0
9713
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...
1
7248
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
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5142
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
3806
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

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.