1

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++ ? ? ? ?

omni
  • 530
  • 1
  • 5
  • 16

5 Answers5

2

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/

1
std::stringstream s(std::string("3.1415927"));
double d;
s >> d;
1

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 ;
Community
  • 1
  • 1
Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682
0

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
aldeb
  • 5,378
  • 3
  • 22
  • 46
0
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.

Dineshkumar
  • 3,887
  • 4
  • 24
  • 42