Thread: What's wrong with sum up two string of integer?

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    77

    What's wrong with sum up two string of integer?

    Code:
    void sumString(char *a, char *b, int len)
    {
    	int i;
    	for (i = 0; i < len; i++)
    		a[i] = (char)(((int)a[i]-48 + (int)b[i]-48) % 10);
    	for (i = 0; i < len; i++)
    		printf("%c", a[i]);
    	printf("\n");
    }
    I wanna implement "1234"+"2345" = "3579" but It displays nothing.

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    (a[i]-'0' + b[i]-'0') + '0';
    a[i]-'0' + b[i];
    Same thing. You should make sure to deal with non-numeric input. And it's a little funky that you just modify the string a, I don't know, unless the user expects that.

  3. #3
    Registered User
    Join Date
    Apr 2005
    Posts
    77
    yes, I want to modify string a, can you write it in details?

  4. #4
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Well, it's just kind of a peculiar sideeffect. Like, I guess it's just a question of interpretation. I mean, I'll draw an analogous situation in C++.

    Code:
    class number_string 
    { 
        number_string & operator += (const number_string &);
        number_string operator + (const number_string &) const;
    };
    The first operator += does modify 'this' string, like string 'a' in your case. But the second one gives back a different number_string completely in summing 'this' and 'other' number_string's. To me, that second behavior is what is expected of the sumString, but, I don't know, it's really pretty ambiguous and up to interpretation. You should just make it clear that your function does modify 'a'.

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    don't forget that 9+9=18
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  4. Integer to string?
    By Blackroot in forum C++ Programming
    Replies: 2
    Last Post: 02-23-2006, 06:13 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM