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.