Click to See Complete Forum and Search --> : adding char * as unsigned int


LHernandez
October 31st, 2002, 06:51 PM
Please HELP:

This is the declaration of a function that adds together two unsigned integer numbers represented as strings:

void Add(const char * s1, const char * s2, char * result);

The function returns the result in a caller-supplied buffer
assuming that it is always big enough.

E.g. char result[50];

Add(“1273”, “16”, result);

Will return “1289” in the result buffer.

How can I write an implementation of the function in C++ w/o
using atoi(), itoa() or other standard functions for conversion.

owenrb
October 31st, 2002, 07:37 PM
Why not use those "char-to-num" or "num-to-char" predefined functions?
It will save you lot of codes.

qarauf
October 31st, 2002, 07:38 PM
Here is the code for understanding
void Add(const char * s1, const char * s2, char * result){
int nNum1,nNum2,nResult;
char test[20];
nNum1=atoi(s1);
nNum2=atoi(s2);
nResult=nNum1+nNum2;

itoa(nResult,result,10);


}
How to call

char * result=new char[20];
Add("1273","16",result);

Here is the professional code

void Add(const char * s1, const char * s2, char * result){
itoa(atoi(s1)+atoi(s2),result,10);
}

stober
November 1st, 2002, 05:40 AM
you can not use any of the standard C library functions that convert from strings to ints. So here is how I would do it:

int ConvertToInt(const char* value)
{
int n = 0;
if(value != NULL)
{
while(*value != 0)
n = (n * 10) + *value++ - '0';
}
return n;
}
void Add(const char * s1, const char * s2, char * result)
{

int i1 = ConvertToInt(s1);
int i2 = ConvertToInt(s2);
int i3 = i1 + i2;
sprintf(result,"%d", i3);

}