Reading numbers form a CString and adding them

Posted on 2004-11-10
Medium Priority
Last Modified: 2013-11-20
I have a CString, say:

CString testString = "abc123";

I want to add the 123, add convert the new number to a string.

I don't need to search the string as I know the positons of the digits I want to add (in this case positions 3,4, and 5..... 0 based)

thanks for any help!
Question by:galneweinhaw
  • 2
  • 2
LVL 86

Expert Comment

ID: 12547836
You could use

int n = 123;
CString testString = "abc";
CString numString = testString.Right(testString.Length() - 3); // get a string onlys containing the numbers
testString = testString.Left(3); // cut off the old numbers

int tmp = atoi((LPCTSTR)numString);

numString.Format("%d", n + tmp);

testString = testString + numString; // put the parts together again

Author Comment

ID: 12548023
Thanks, but I don't think I was very clear on what I need to do, I'll try to clarify:

I have a CString "@@@@12@@@"  where 1 and 2 are the two numbers I want to add and @ may be #'s or letters.

I want to do 1 + 2 = 3

then convert the 3 to a CString.

the numbers will always be single digit (0-9)

thanks again.

LVL 86

Accepted Solution

jkr earned 2000 total points
ID: 12548066
Aaah, OK, then it is

CString testString = "abc123";
CString strNum;
int n1 = testString[3] - '0'; // subtracting ASCII '0' will give the numeric value
int n2 = testString[4] - '0';

strNum.Format("%d", n1 + n2);


Author Comment

ID: 12548214

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

If you use Adobe Reader X it is possible you can't open OLE PDF documents in the standard. The reason is the 'save box mode' in adobe reader X. Many people think the protected Mode of adobe reader x is only to stop the write access. But this fe…
In this post we will learn different types of Android Layout and some basics of an Android App.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
There may be issues when you are trying to access Outlook or send & receive emails or due to Outlook crash which leads to corrupt or damaged PST file. To eliminate the corruption from your PST file, you need to repair the corrupt Outlook PST file. U…
Suggested Courses
Course of the Month9 days, 1 hour left to enroll

621 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