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.

Dani AI

Generated

As noted, the operation requires converting the text to a numeric type, performing the addition, then converting the result back to text. Since wanted only standard C++, here are concise, practical options that were not shown earlier.

A simple C++11+ approach uses std::stoi / std::to_string:

#include <string>
#include <iostream>

int main() {
    std::string a = "1", b = "2";
    int sum = std::stoi(a) + std::stoi(b);
    std::string c = std::to_string(sum); // "3"
    std::cout << c << '\n';
}

For the very common special case of single-digit characters, a tiny arithmetic trick avoids parsing libraries and is fastest:

std::string a = "1", b = "2";
char result = (a[0] - '0') + (b[0] - '0') + '0'; // '3'
std::string c(1, result); // "3"

Notes and troubleshooting:

  • std::stoi / std::stol / std::stoll throw std::invalid_argument or std::out_of_range on bad input; wrap calls in try/catch or pre-validate with std::isdigit.
  • std::from_chars (C++17) offers a non-throwing, faster parse and returns an error code—prefer it in performance-sensitive code.
  • Watch for empty strings before indexing (the char trick assumes a and b are non-empty), leading/trailing whitespace, signs, multi-digit values, and overflow. Use the appropriate width (long long/stoll) when needed.
  • The single-quote vs double-quote issue: single quotes denote a char, double quotes a string literal; using the wrong one will either not compile or give unexpected types.

For environments limited to pre-C++11, the standard stream-based parsing approach (as demonstrated earlier in this thread) is the compatible fallback.

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.