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

3

5 Answers 5

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/

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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 ;

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.