Converting a string like "2.12e-6" to a double - c++

Is there a built in function in c++ that can handle converting a string like "2.12e-6" to a double?

strtod()

atof should do the job. This how its input should look like:
A valid floating point number for atof is formed by a succession of:
An optional plus or minus sign
A sequence of digits, optionally containing a decimal-point character
An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits.

If you would rather use a c++ method (instead of a c function)
Use streams like all other types:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <boost/lexical_cast.hpp>
int main()
{
std::string val = "2.12e-6";
double x;
// convert a string into a double
std::stringstream sval(val);
sval >> x;
// Print the value just to make sure:
std::cout << x << "\n";
double y = boost::lexical_cast<double>(val);
std::cout << y << "\n";
}
boost of course has a convenient short cut boost::lexical_cast<double> Or it is trivial to write your own.

Related

how to get all decimal number from string in c++

I'm trying to get value (all decimal number) from a text in c++. But I have a problem and I couldn't solve it
#include "pch.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("C:\\thefile.txt");
float a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
thefile.txt:
34.123456789 77.987654321
When I run the above code,
a = 34.1235
b = 77.9877
but I want
a = 34.123456789
b = 77.987654321
what should I do?
EDIT: I don't want to print out of a and b. I just want they get the exact values.net
You can't.
A float can only give you six (ish) decimal significant figures. The values in your file, after conversion from string, cannot be held in a float.
First, you need to switch to double, otherwise you won't even have a variable with the full numerical value.
Then, for output, be careful to specify the precision you want.
Please remain aware of the foibles of floating-point, and consider sticking with strings, depending on what you're doing with this data.
There are two main things i see in your code.
float precision is not enough for you data you need double data type.
you need to set proper cout precision to get your desired output.
This code will work for you.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("newfile.txt");
double a, b;
std::cout.precision(11);
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
you should read your inputs into a string and then convert them into double (depending on enough precision in float on your computer). you can directly display strings. A possible answer is here.
string word;
openfile >> word;
double lol = atof(word.c_str());

Parsing and turning a string into a number

I have an input file which I'm reading in with the basic myFile >> variable since I know the format and the format will always be correct. The file I'm reading in is formatted as instruction <num> <num> and to make >> work, I'm reading everything in as a string. If I have 3 variables, one to take in each piece of the line, how can I then turn string <1> (for example) into int 1? I know the string's first and last characters are brackets which need to be removed, then I could cast to an int, but I'm new to C++ and would like some insight on the best method of doing this (finding and removing the <>, then casting to int)
use stringstream
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string str = "<1>";
int value;
std::stringstream ss(str);
char c;
ss >> c >> value >> c;
std::cout << value;
}
First to get the middle character out you can just do char myChar = inputString.at(1);. Then you can do int myInt = (int)myChar;
Even if you remove the <> characters, your still importing the file content into a string using >> so you still need to cast it to an int. If you have only 1 value, you can follow what Nicholas Callahan wrote in the previous answer, but if you have multiple characters you want to read as int, you dont have a choice but to cast.
You can also resort to sscanf.
#include <cstdio>
#include <iostream>
#include <string>
int main()
{
std::string str = "<1234>";
int value;
sscanf(str.c_str(), "<%d>", &value);
std::cout << value << std::endl;
}

Convert double to string with n decimal places without trailing zeros

1)double d = 1.234567899;
Convert this number to string with 8 decimal places without truncation.
So,expected output is "1.23456789", truncating last 9.
and
2)if d = 1.2345699;
so Solution should not append 0 upto 8th decimal place.expected output "1.2345699".
I have tried many solutions,ended up with stringstream c++ class. 2nd problem is solved but first one still persist.
Is there any way to achieve the output?
Thanks in advance.
If you want to truncate part of the string representation without rounding, you need to do that manually:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <limits>
int main()
{
std::stringstream s;
double d = 1.234567899;
// print it into sstream using maximum precision
s << std::fixed << std::setprecision(std::numeric_limits<double>::digits10) << 1.234567899;
std::string res = s.str();
// Now the res contains something like 1.234567899000000
// so truncate 9000000000 by hand
size_t dotIndex = res.find(".");
std::string final_res = res.substr(0, dotIndex + 9);
std::cout << final_res << std::endl;
return 0;
}
Would you be served by first Flooring the double to the required decimals?
If so, have a look at http://www.cplusplus.com/forum/beginner/3600/
Truncating exactly as you want:
sprintf(str, "%1.10f", d);
memset(str+10, 0x00, 1);

How to display an integer literally as a character

I have an integer 1 and i want to display it as a character '1' in C++. So far I have only managed to convert it from say integer 65 to character 'A'.
How do you stop this ?
int theDigit = 1;
char ch = theDigit+'0';
This works because it's guaranteed1 that the sequence of characters '0'...'9' is contiguous, so if you add your number to '0' you get the corresponding character. Obviously this works only for single digits (if theDigit is e.g. 20 you'll get an unrelated character), if you need to convert to a string a whole number you'll need snprintf (in C) or string streams (in C++).
C++11, [lex.charset] ΒΆ3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
By the way, I suppose that they didn't mandate contiguity also in the alphabetical characters just because of EBCDIC.
Use the stringstream.
int blah = 356;
stringstream ss;
string text;
ss << blah;
ss >> text;
Now text contains "356"(without quotes). Make sure to include the header files and use the namespace if you are going to copy my code:
#include <sstream> //For stringstream
#include <string>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
int i = 3;
char buffer [25];
itoa (i, buffer, 10);
printf ("Integer: %s\n",buffer);
Integer: 3
You did just ask about printing an integer, so the really simple c++ answer is:
#include <iostream>
int main()
{
int value = 1;
std::cout << value << endl;
return 0;
}

C++ string to double conversion

Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.
I used the code(snippet)
string word;
openfile >> word;
double lol=word;
I receive the error that
Code1.cpp cannot convert `std::string' to `double' in initialization
What does the error mean exactly? The first word is the number 50. Thanks :)
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999 (which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
Coversion from string to double can be achieved by
using the 'strtod()' function from the library 'stdlib.h'
#include <iostream>
#include <stdlib.h>
int main ()
{
std::string data="20.9";
double value = strtod(data.c_str(), NULL);
std::cout<<value<<'\n';
return 0;
}
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}