1

Possible Duplicate:
How to convert a number to string and vice versa in C++

in csharp

string s1="12345"
string s2="54321"

public double (string s1,string s2)
{
  convert.todouble(s1) +convert.to-double(s2)
}

how i do in c++ because there is no conversion classs

Community
  • 1
  • 1

6 Answers6

7

In addition to the other answers, the easiest way (in C++11 at least) would be:

double add(const std::string &s1, const std::string &s2)
{
    return std::stod(s1) + std::stod(s2);
}
Christian Rau
  • 45,360
  • 10
  • 108
  • 185
4

If your compiler supports C++11, there is a function stod that converts a string to a double.

Your function will be just

return std::stod(s1) + std::stod(s2);
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2

Use boost::lexical_cast for example.

double func (const std::string& s1, const std::string& s2)
{
    return boost::lexical_cast<double>(s1) + boost::lexical_cast<double>(s2);
}

or use std::stringstream, strtod etc.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
2
double doubleFromString(const std::string &str)
{
    std::istringstream is(str);
    double res;
    is >> res;
    return res;
}
Andrew
  • 24,218
  • 13
  • 61
  • 90
1

c++11 contains std::stod which converts a string to a double. Otherwise you can use stringstreams or boost::lexical_cast<double>. Therefore your options are:

return std::stod(s1) + std::stod(s2); //(c++11 only), or:
return boost::lexical_cast<double>(s1) + boost::lexical_cast<double>(s2); //or:
std::stringstream ss1(s1);
std::stringstream ss2(s2);
double a, b;
ss1>> a;
ss2>>b;
return a+b;

Of course you could also go the c route and use sprintf.

Grizzly
  • 19,595
  • 4
  • 60
  • 78
-1

I would go with using string streams, as you don't need support to c++11.

This article in cplusplus.com answers your question: http://www.cplusplus.com/reference/iostream/istringstream/istringstream/

But this is what I would do:

#include <string>
#include <sstream>

double function (std::string s1, std::string s2)
{
    std::istringstream iss (std::string(s1 + " " + s2), std::istringstream::in);
    double a, b;
    iss >> a;
    iss >> b;

    return a + b;
}