Hey, ive got two string types

string string1 = '1';
string string2 = '2';
string string3 = string1 + string2;

Ok, ive simplified my code. I would like string3 to equal '3', and not '12'. I dont know anything about casting.

Please dont tell me to use an integer datatype because as i said, ive simplified my code.

Recommended Answers

All 7 Replies

ok, the title of this thread makes no sense - i was thinking about making a timer, and changed my mind and asked tis question instead, sorry about that. thanks guys

There has to be some conversion. The two operands need to be converted to an integer type, and then the result of addition needs to be converted to a string. For example using boost::lexical_cast for brevity:

string string3 = boost::lexical_cast<string>(
    boost::lexical_cast<int>(string1) + 
    boost::lexical_cast<int>(string2));

boost::lexical_cast is basically just a wrapper around string streams. You can simulate it quite easily if installing the Boost library is prohibitive for some reason:

#include <sstream>
#include <typeinfo>

template <typename Target, typename Source>
Target lexical_cast(Source arg)
{
    std::stringstream interpreter;
    Target result;
 
    if (!(interpreter << arg && interpreter >> result))
        throw std::bad_cast();
 
    return result;
}

Alternatively you could perform manual addition similar to how an arbitrary precision math library might work, but that's probably excessive.

thanks for that, which library needs to be included to use the boost class? is it standard c++?

you would be correct in thinking that i can only use standard c++. Could you show in a little more detail the way in which the second example you gave works, using the operands that i gave? Thanks by the way i really appreciate it.

Just take away the boost namespace qualification:

#include <iostream>
#include <sstream>
#include <string>
#include <typeinfo>

using namespace std;

template <typename Target, typename Source>
Target lexical_cast(Source arg)
{
    std::stringstream interpreter;
    Target result;
 
    if (!(interpreter << arg && interpreter >> result))
        throw std::bad_cast();
 
    return result;
}

int main()
{
    string string1 = "1";
    string string2 = "2";
    string string3 = lexical_cast<string>(
        lexical_cast<int>(string1) + 
        lexical_cast<int>(string2));

    cout << string1 << " + " << string2 << " = " << string3 << '\n';
}
commented: very informative and useful +3

Thankyou very much, that's exactly what i was looking for. solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.