|
-
October 31st, 2002, 07:51 PM
#1
adding char * as unsigned int
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.
-
October 31st, 2002, 08:37 PM
#2
Why not use those "char-to-num" or "num-to-char" predefined functions?
It will save you lot of codes.
Last edited by owenrb; October 31st, 2002 at 08:43 PM.
-
October 31st, 2002, 08:38 PM
#3
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);
}
-
November 1st, 2002, 06:40 AM
#4
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:
Code:
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);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|