Thread: Arithmetic with a string.

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    3

    Arithmetic with a string.

    I have a string "I10014" stored as a char, I need to do arithmetic on each of the numbers individually i.e. 1 * 5, so that I have a result for each sum and then add them all up to have a total. But I want to do it in a function, so will need to pass the string to it.
    Please help.

  2. #2
    Registered User Pioneer's Avatar
    Join Date
    Dec 2002
    Posts
    59
    You can change a character to the number equivalent by subtracting '0'.
    Code:
    #include <stdio.h>
    
    add(char *nums){
        int sum=0;
    
        if (*nums=='A'){
            while (*++nums!='\0')
                sum+=*nums-'0';
            printf("The total is %d\n", sum);
        }
    }
    
    main(){
        char b[]="A10014";
    
        add(b);
    }
    Real respect comes from those that have the knowledge to understand what you've done and the experience to appreciate it. It's the Crack Cocaine of programming.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM