0

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.

2
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by lexusdominus
0

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

0

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.

0

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

Edited by lexusdominus: n/a

0

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.

1

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';
}
Votes + Comments
very informative and useful
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.