Solved

How two add the values of two strings

Posted on 2003-11-08
1
225 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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…
C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

756 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