String to long double conversion in c++98 - c++

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.

Related

how to turn a string of numbers to binary in C++?

Hi I have a string that looks like this:
std::string myString = "123456789";
Is there a way for me to turn that string of a decimal number to a binary number?
Firstly, you want to convert the string representing a number into an actual integer.
As stated by some others: std::stoi "string to int". Depending on the size of the numbers, you may want to use std::stoull. this is the same thing but for long long, a 64 bit integer.
Next you want to convert that number back into string. the easiest thing to use that provides this functionality is std::bitset and its to_string member function. The constructor of bitset requires an unsigned long long, so we'll use std::stoull, the unsigned variant.
This can all be combined into a single line of code:
myString = std::bitset<64>{ std::stoull(myString) }.to_string(); // 64 bits to fit a long long
After this operation, You'll be left with a string that looks like this: 0000000000000000000000000000000000000111010110111100110100010101
You may want to get rid of the zero's up front.
We can use the string's find and erase
myString.erase( 0, myString.find('1') );
This will erase all characters from position 0 until the first 1's position.
If you want to parse string to int, here is how you do it:
std::string strDec = "123456789";
int i = std::stoi(strDec);
If you then want to convert int to string but this time in binary representation, here is a way to do that:
std::string strBin = std::bitset<32>(i).to_string();
Demo
Or, you can use {fmt} library:
#include <fmt/core.h>
int main() {
std::string strDec = "123456789";
std::string strBin = fmt::format("{:032b}", std::stoi(strDec));
}
Demo

Appending long double literal suffix to user inputs in c++

I have a class that has a long double vector:
MyClass{
vector<long double> myvec;
public:
MyClass(){ //Constructor }
// Some memeber functions that operate on the vector
};
I have overloaded the input operator an I'm taking input from a user that are then pushed into the vector. The problem that I'm having is if the user inputs a number that is out of range of double, the code should append append the long double suffix to the input with out the user having too. This is what I have tried so far:
long double input;
...
input = (long double)(input + "L");
myvec.push_back(input);
I thought of using scanf, but I'm not sure how safe that is to use when overloading the input operator.
Use std::stold to convert input text to long double. There is no need for a suffix; stold will do it right. The suffix is needed in source code to tell the compiler what type the text represents. When you're reading from an external source the compiler isn't involved, so you have to sort out the type yourself.
Suffixes are only for literal values, e.g. auto x = 12345.0L. You use them to prevent implicit conversions since the default type of a floating point literal is double.
You can't use them on a named variable.
The question is how you get your input?

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/

Which function should be use to converting string to long double?

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

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."