Solved

How two add the values of two strings

Posted on 2003-11-08
1
193 Views
Last Modified: 2010-04-02
Is there an easy way to add the values of two strings(containing integers) together?

Example:
string1={1234};
string2={4321};

How do you add the values together to get:

string3 = val of string1 + val of string2 ;
//string3 = {5555}

Is there a built in function for this?
0
Comment
Question by:m0neyman
1 Comment
 
LVL 8

Accepted Solution

by:
mnashadka earned 125 total points
ID: 9708340
atoi will put the strings into ints, like:
char s1[] = "1234";
char s2[] = "4321";
int value3 = atoi(s1) + atoi(s2);

If you're actually using strings then you need to convert them to const char *'s using c_str():
string s1 = "1234";
string s2 = "4321";
int value3 = atoi(s1.c_str()) + atoi(s2.c_str());

Then you can either use sprintf (for the old C way) or an ostringstream to put the int back into a string:
char s3[10];
sprintf(s3, "%d", value3);

or
ostringstream result;
result << value3;
string s3 = result.str();

Hope this helps.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now