Solved

How two add the values of two strings

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Which IDE to use to begin C++ training? 5 65
Best book to learn C++ 4 84
White board coding practice 3 90
Safe conversion? 4 72
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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 pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

861 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