sg552
sg552

Reputation: 1543

String addition or subtraction operators

How to add or subtract the value of string? For example:

    std::string number_string;
    std::string total;

    cout << "Enter value to add";
    std::getline(std::cin, number_string;
    total = number_string + number_string;
    cout << total;

This just append the string so this won't work. I know I can use int data type but I need to use string.

Upvotes: 0

Views: 4632

Answers (2)

David Stone
David Stone

Reputation: 28773

You will want to work with integers the entire time, and then convert to a std::string at the very end.

Here is a solution that works if you have a C++11 capable compiler:

#include <string>

std::string sum(std::string const & old_total, std::string const & input) {
    int const total = std::stoi(old_total);
    int const addend = std::stoi(input);
    return std::to_string(total + addend);
}

Otherwise, use boost:

#include <string>
#include <boost/lexical_cast.hpp>

std::string sum(std::string const & old_total, std::string const & input) {
    int const total = boost::lexical_cast<int>(old_total);
    int const addend = boost::lexical_cast<int>(input);
    return boost::lexical_cast<std::string>(total + addend);
}

The function first converts each std::string into an int (a step that you will have to do, no matter what approach you take), then adds them, and then converts it back to a std::string. In other languages, like PHP, that try to guess what you mean and add them, they are doing this under the hood, anyway.

Both of these solutions have a number of advantages. They are faster, they report their errors with exceptions rather than silently appearing to work, and they don't require extra intermediary conversions.

The Boost solution does require a bit of work to set up, but it is definitely worth it. Boost is probably the most important tool of any C++ developer's work, except maybe the compiler. You will need it for other things because they have already done top-notch work solving many problems that you will have in the future, so it is best for you to start getting experience with it. The work required to install Boost is much less than the time you will save by using it.

Upvotes: 1

StilesCrisis
StilesCrisis

Reputation: 16290

You can use atoi(number_string.c_str()) to convert the string to an integer.

If you are concerned about properly handling non-numeric input, strtol is a better choice, albeit a little more wordy. http://www.cplusplus.com/reference/cstdlib/strtol/

Upvotes: 2

Related Questions