Solved

How two add the values of two strings

Posted on 2003-11-08
1
206 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

932 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

9 Experts available now in Live!

Get 1:1 Help Now