Solved

How two add the values of two strings

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

[Webinar] Code, Load, and Grow

Managing multiple websites, servers, applications, and security on a daily basis? Join us for a webinar on May 25th to learn how to simplify administration and management of virtual hosts for IT admins, create a secure environment, and deploy code more effectively and frequently.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
FMX enumerated colours 2 151
Installshield for Embarcadero EX 10.1 Berlin 4 86
C++ help/ Toy problem 19 67
learn programming 8 90
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
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 user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

733 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