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

1
  • @valdo: Except that C++'s a high-level programming language too. Commented Jul 29, 2012 at 11:03

6 Answers 6

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

if function retrun type is int???so its same???
If the string contains an int, there is also std::stoi and a set of others for that.
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);

1 Comment

if function retrun type is int???so its same???
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.

Comments

2
double doubleFromString(const std::string &str)
{
    std::istringstream is(str);
    double res;
    is >> res;
    return res;
}

Comments

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.

Comments

-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;
}

2 Comments

Nice usage of string concatenation to avoid the costly istringstream constructor.
and i thought that was a naughty hack! thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.