Which function should be use to converting string to long double? - c++

Note that in general, double is different from long double.
strtod converts string to double, but which function should be use to converting string to long double?

In C++03, use boost::lexical_cast, or:
std::stringstream ss(the_string);
long double ld;
if (ss >> ld) {
// it worked
}
In C99, use strtold.
In C89, use sscanf with %Lg.
In C++11 use stold.
There may be subtle differences as to exactly which formats each one accepts, so check the details first...

You've tagged your question as "C++", so I'm going to give you a C++ answer:
Why not just use streams?
std::stringstream ss(myString);
long double x;
ss >> x;

In c++, I can only recommend boost::lexical_cast (or in general via the IOStreams).
In c ? no idea.

You can use istream to read long double from string. See here http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/
If you like scanf family of functions, read with %Lf

Related

String to long double conversion in c++98

Anyone know how to convert a string to long double? For example lets say we have
string S = "3.236568949"
I want to take what inside the string and convert it to a long double variable x.
Note: In c++11 their exist stold function do so but I'm using c++98 not c++11.
Also I don't need to cout the string with certain precision because I know setprecision function already but what I want is just to convert to long double. In other wards,I need x to equal the exact number inside the string and not an approximated version of the number. Finally I want to tell you that my string contains a valid number.
you can use the C function :
#include <stdlib.h>
int main(){
char* convertme="3.236568949";
double converted=atof(convertme);
return 0;
}
You can use a std::stringstream to convert the string into a long double. The std::stringstream acts just like cin but instead of getting the input from the user you load it into the stream with a std::string. That looks like
std::string data = "3.236568949"
std::stringstream ss(data);
long double ld;
ss >> ld;
Do note that when dealing with floating point numbers you are going to have to deal with imprecision. For more on this see Is floating point math broken?
You can use strtold() function from C99:
long double d = strtold( str.c_str(), nullptr );
to convert std::string to long double. Though floating point representation is approximate so nobody would guarantee that value after conversion is exactly the same is in your string.

How to convert a string to a signed float? [duplicate]

This question already has answers here:
std::string to float or double
(16 answers)
Closed 8 years ago.
like :
string num = "-0.25";
how can I convert it to a signed float?
C++11: std::stof(num) to convert to float; also stod for double and stold for long double.
Historically: std::strtod (or std::atof if you don't need to check for errors); or string streams.
strtod() is a good bet for C.
I have no idea if C++ has other bets.
The std::stof function should work fine.
You can use istringstream:
std::string num = "-0.25";
std::istringstream iss ( num);
float f_val = 0;
iss >> f_val;
You can convert the string to a signed float by using the function atof. Like :
float myValue = (float)atof("0.75");
Note that you should also checked if the passed value is a valid numerical value otherwise the behaviour could be unpredictable.
There is also an other solution :
string mystr ("1204");
int myint;
stringstream(mystr) >> myint;
You can use the atof function.
http://www.cplusplus.com/reference/cstdlib/atof/
For C++ you can also use std::stof
http://www.cplusplus.com/reference/string/stof/

C++ Int to String by using ostringstream or stringstream

I've been using stringstream to convert Integer to String, but then I realized same operation can be done with ostringstream.
When I use .str() what is the difference between them? Also, is there more efficient way to convert integers to strings?
Sample code:
//using ostringstream
ostringstream s1;
int i=100;
s1<<i;
string str_i=s1.str();
cout<<str_i<<endl;
//using stringstream
stringstream s2;
int i2=100;
s2<<i2;
string str_i2=s2.str();
cout<<str_i2<<endl;
There is a third that you didn't mention, istringstream, which you can't use (well you could but it would be different, you can't << to an istringstream).
stringstream is both an ostringstream and an istringstream - you can << and >> both ways, in and out.
With ostringstream, you can only go in with <<, and you cannot go out with >>.
There isn't really a difference, you can use either way to convert strings to integers. If you want to do it the fastest way possible, I think boost::lexical_cast has that title, or you could use the itoa function which may be faster than stringstream, but you lose the advantages of C++ and the standard library if you use itoa (you have to use C-strings, etc).
Also, as Benjamin Lindley informed us, C++11 has the ultramagical std::to_string.

float <-> std::string conversion alternative?

is there any alternative to atof, strtod, lexical_cast, stringstream or sprintf?
that is:
fast
C++ way (std::string instead of char*)
safe (no buffer overrun risk)
valid (return NaN if conversion couldn't be made)
no external library (independent)
I prefer more like this , a simple function, optimized, and to the point
reason :
atof and strtod is C function and they are not returning NaN upon failure, I prefer working on std::string, so I just asking if anyone already writing some wrapper to std::string that I can use (if you don't mind).
lexical_cast has boost dependency
stringstream is slow
sprintf has buffer overflow risk and its C function
I'd look at Boost Spirit
http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/qi/reference/numeric/real.html
At least the benchmarks of the formatters (that is float -> string) consistently turn out as top-of-the-bill*1*
Also the exact input format specification and semantics when parsing can be configured very nicely using a policy class.
Here is my absolute min-dependency use of qi::any_real_parser<> and the list of dependendencies it touches:
#include <boost/spirit/include/qi_real.hpp>
namespace qi = boost::spirit::qi;
int main()
{
const char input[] = "3.1415926";
const char *f(input);
const char *l(f+strlen(input));
qi::any_real_parser<double> x;
double parsed;
x.parse(f, l, qi::unused, qi::unused, parsed);
return 0;
}
boost/concept
boost/config
boost/detail
boost/exception
boost/fusion
boost/iterator
boost/math
boost/mpl
boost/optional
boost/preprocessor
boost/proto
boost/range
boost/regex
boost/spirit
boost/typeof
boost/type_traits
boost/utility
boost/variant
aligned_storage.hpp,assert.hpp,blank_fwd.hpp,blank.hpp,call_traits.hpp,checked_delete.hpp,concept_check.hpp,config.hpp,cstdint.hpp,current_function.hpp,foreach_fwd.hpp,foreach.hpp,get_pointer.hpp,implicit_cast.hpp,iterator.hpp,limits.hpp,math_fwd.hpp,next_prior.hpp,noncopyable.hpp,none.hpp,none_t.hpp,optional.hpp,ref.hpp,static_assert.hpp,swap.hpp,throw_exception.hpp,type.hpp,utility.hpp,variant.hpp,version.hpp
1 e.g. http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance/double_performance.html
If you want to convert from numerical types to std::string there's a std::to_string function available in the latest standard.
Unfortunately as I've found out recently, in Visual Studio 2010 it is somewhat limited because there are only three overloads available for it; long double, long long, and unsigned long long. This causes issues when trying to use them from within templates.
The fast format library should be able to do the kinds of transformations you're looking for, at least for writing a float out. It does not handle parsing of a float, however.

Cast a pointer to char to a double C++

How can i cast a pointer to char to a double ?
I am using command line arguments and one of the argument is a double but in the program is it passed as a char*.
I tried using static_cast and reinterpret_cast but with no effect.
Pure C++ solution:
#include <sstream>
// ...
std::stringstream ss;
ss << your_char_pointer;
ss >> your_double;
Boost solution:
#include <boost/lexical_cast.hpp>
// ...
your_double = boost::lexical_cast<double>(your_char_pointer);
Try Boost lexical_cast.
double val = atof(*charpointer)
atof stands for "all to float", (or "array to float"), and does exactly what you want. If it cannot convert the char array, it returns 0.0. See: Man atof
That's not how type conversion in C/C++ works. You must pass the string through a numeric parser manually. E.g.
char *thestring;
double d;
d = atof(thestring);
If the double comes from the command line, it is actually a real string, you have to convert it to a double, you can't just cast it.
For example, you can use strtod for this task :
double d = strtod (mystr,NULL);
You're trying to convert a string (represented by the char *) into a double. This is not something you can do with a regular built in type cast in C++ as all they do is reinterpret the bit pattern that is being referenced by the pointer. Instead you have to parse the command line argument to extract a double value from the string.
As mentioned, you have several options:
you can use atof for the conversion, but it's hard to determine if the conversion errored because both a string that can't be converted and one representing 0.0 give you the same result
As Fred Larson mentioned, you can use boost::lexical_cast. That's a pretty elegant way to handle the problem and would most likely be my preferred one
You can use iostreams to do the conversion
You can write the conversion code yourself (just kidding)
The atof man page says "The atof() function has been deprecated by strtod() and should not be used in new code."