CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2002
    Location
    San Miguel
    Posts
    66

    Question 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.

  2. #2
    Join Date
    Sep 2002
    Location
    Philippines
    Posts
    197
    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.

  3. #3
    Join Date
    Oct 2002
    Posts
    14
    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);
    }

  4. #4
    Join Date
    Jun 2002
    Posts
    1,417
    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
  •  





Click Here to Expand Forum to Full Width

Featured