how to convert string value into double format in c++ - c++

How do I convert a string value into double format in C++?

If you're using the boost libraries, lexical cast is a very slick way of going about it.

Use stringstream :
#include <sstream>
stringstream ss;
ss << "12.34";
double d = 0.0;
ss >> d;

You can do with stringstream.
You can also catch invalid inputs like giving non-digits and asking it to convert to int.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream s;
string input;
cout<<"Enter number: "<<endl;
cin>>input;
s.str(input);
int i;
if(s>>i)
cout<<i<<endl;
else
cout<<"Invalid input: Couldn't convert to Int"<<endl;
}
If conversion fails, s>>i returns zero, hence it prints invalid input.

Related

c++ istringstream() function converting string to int raises error

I have a string of digits. I am trying to print it as an int type each single digit in the string using istringstream. It works fine if pass whole string as argument to conversion function in main but if I pass it by index, it raises error.
How to make this code work using index to print each single digit in string array as an int.
Here is my code.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int strToNum(string str)
{
istringstream ss(str);
int n;
ss>>n;
cout<<n;
}
int main()
{
string str = "123";
for(int i=0; i<str.length(); i++)
//strToNum(str); Works fine
strToNum(str[i]); //raises error
}
str[i] is a char, while the strToNum expects a string, hence the type error.
It raises error because str[i] is a char
however , strToNum(string str) excepts a string
Try this :
for(int i=0; i<str.length(); i++)
strToNum(string(1,str[i])); //Convert char to string
See here
Others have explained your error. This is how you could make it work:
strToNum( std::string(1, str[i]) );
But I'd do this instead:
for(int i=0; i<str.length(); i++)
cout << str[i] - '0';
But ask yourself if you really need this. Are you interested in the value or the representation? If the latter, just print chars.
You don't need istringstream at all.
int strToNum(char ch)
{
cout << ch;
}
Actually I use a template function to perform this task, which is a more useful way to write the function that originated this thread ( because this single function can convert a string to any type of number: int, float, double, long double ):
#include "stdafx.h"
#include <string>
#include <iostream>
#include <Windows.h>
#include <sstream>
#include <iomanip>
using namespace std;
template <typename T>
inline bool StrToNum(const std::string& sString, T &tX)
{
std::istringstream iStream(sString);
return (iStream >> tX) ? true : false;
}
void main()
{
string a="1.23456789";
double b;
bool done = StrToNum(a,b);
cout << a << endl;
cout << setprecision(10) << b << endl;
system ("pause");
}
setprecision(10) ( iomanip ) is required otherwise istringstream will hide some decimals

Converting Input string to float/double C++

So I know how to do it in C#, but not C++. I am trying to parse giver user input into a double (to do math with later), but I am new to C++ and am having trouble. Help?
C#
public static class parse
{
public static double StringToInt(string s)
{
double line = 0;
while (!double.TryParse(s, out line))
{
Console.WriteLine("Invalid input.");
Console.WriteLine("[The value you entered was not a number!]");
s = Console.ReadLine();
}
double x = Convert.ToDouble(s);
return x;
}
}
C++
?
?
?
?
Take a look at atof. Note that atof takes cstrings, not the string class.
#include <iostream>
#include <stdlib.h> // atof
using namespace std;
int main() {
string input;
cout << "enter number: ";
cin >> input;
double result;
result = atof(input.c_str());
cout << "You entered " << result << endl;
return 0;
}
http://www.cplusplus.com/reference/cstdlib/atof/
std::stringstream s(std::string("3.1415927"));
double d;
s >> d;
This is simplified version of my answer here which was for converting to an int using std::istringstream:
std::istringstream i("123.45");
double x ;
i >> x ;
You can also use strtod:
std::cout << std::strtod( "123.45", NULL ) << std::endl ;
Using atof:
#include<cstdlib>
#include<iostream>
using namespace std;
int main() {
string foo("123.2");
double num = 0;
num = atof(foo.c_str());
cout << num;
return 0;
}
Output:
123.2
string str;
...
float fl;
stringstream strs;
strs<<str;
strs>>fl;
this converts the string to float.
you can use any datatype in place of float so that string will be converted to that datatype. you can even write a generic function which converts string to specific datatype.

C++ Converting a String to Double

I've been trying to find the solution for this all day! You might label this as re-post but what I'm really looking for is a solution without using boost lexical cast. A traditional C++ way of doing it would be great. I tried this code but it returns a set of gibberish numbers and letters.
string line;
double lineconverted;
istringstream buffer(line);
lineconverted;
buffer >> lineconverted;
And I alse tried this, but it ALWAYS returns 0.
stringstream convert(line);
if ( !(convert >> lineconverted) ) {
lineconverted = 0;
}
Thanks in advance :)
EDIT: For the first solution I used (gibberish).. Here's a snapshot
#include <sstream>
int main(int argc, char *argv[])
{
double f = 0.0;
std::stringstream ss;
std::string s = "3.1415";
ss << s;
ss >> f;
cout << f;
}
The good thing is, that this solution works for others also, like ints, etc.
If you want to repeatedly use the same buffer, you must do ss.clear in between.
There is also a shorter solution available where you can initialize the value to a stringstream and flush it to a double at the same time:
#include <sstream>
int main(int argc, char *argv[]){
stringstream("3.1415")>>f ;
}
Since C++11 you could use std::stod function:
string line;
double lineconverted;
try
{
lineconverted = std::stod(line);
}
catch(std::invalid_argument)
{
// can't convert
}
But solution with std::stringstream also correct:
#include <sstream>
#include <string>
#include <iostream>
int main()
{
std::string str;
std::cin >> str;
std::istringstream iss(str);
double d = 0;
iss >> d;
std::cout << d << std::endl;
return 0;
}
If you want to store (to a vector for example) all the doubles of a line
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::istream_iterator<double> in(std::cin);
std::istream_iterator<double> eof;
std::vector<double> m(in,eof);
//print
std::copy(m.begin(),m.end(),std::ostream_iterator<double>(std::cout,"\n"));
}

Emulating sscanf's %*s with istreamstream [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
C++ alternative to sscanf()
I have the following line of code
sscanf(s, "%*s%d", &d);
How would I do this using istringstream?
I tried this:
istringstream stream(s);
(stream >> d);
But it is not correct because of *s in sscanf().
The %*s used with sscanf basically means to ignore a string (any characters up until a whitespace), and then after that you're telling it to read in an integer (%*s%d). The asterisk (*) has nothing to do with pointers in this case.
So using stringstreams, just emulate the same behaviour; read in a string that you can ignore before you read in the integer.
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
ie. With the following small program:
#include <iostream>
#include <sstream>
using namespace std;
int main(void)
{
string s = "abc 123";
int d;
string dummy;
istringstream stream(s);
stream >> dummy >> d;
cout << "The value of d is: " << d << ", and we ignored: " << dummy << endl;
return 0;
}
the output will be: The value of d is: 123, and we ignored: abc.
There is no pointer manipulation in your code.
As AusCBloke has said, you need to read the all of the unwanted characters before the int into a std::string. You also want to ensure that you handle malformed values of s, such as those with any integers.
#include <cassert>
#include <cstdio>
#include <sstream>
int main()
{
char s[] = "Answer: 42. Some other stuff.";
int d = 0;
sscanf(s, "%*s%d", &d);
assert(42 == d);
d = 0;
std::istringstream iss(s);
std::string dummy;
if (iss >> dummy >> d)
{
assert(dummy == "Answer:");
assert(42 == d);
}
else
{
assert(!"An error occurred and will be handled here");
}
}

String in scientific notation C++ to double conversion

I've got a database filled up with doubles like the following one:
1.60000000000000000000000000000000000e+01
Does anybody know how to convert a number like that to a double in C++?
Is there a "standard" way to do this type of things? Or do I have to roll my own function?
Right now I'm doing sth like this:
#include <string>
#include <sstream>
int main() {
std::string s("1.60000000000000000000000000000000000e+01");
std::istringstream iss(s);
double d;
iss >> d;
d += 10.303030;
std::cout << d << std::endl;
}
Thanks!
Something like this? This would be the "C++" way of doing it...
#include <sstream>
using namespace std;
// ...
string s = "1.60000000000000000000000000000000000e+01";
istringstream os(s);
double d;
os >> d;
cout << d << endl;
Prints 16.
You want the standard c function atof ([A]SCII to [F]loat, but it actually uses doubles rather than floats).