isdigit to work with negative numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • george8000
    New Member
    • Jul 2012
    • 3

    isdigit to work with negative numbers

    Ok well i know that isdigit in my code is seeing the negatives as a character and so i made my program give an error message. But i need negative numbers to work how could i get this to work with negative numbers.

    The code is supposed to add the 3 numbers input into the command line argument including negative numbers.


    Code:
    #include <stdio.h>
    #include <stdlib.h> 
    #include <ctype.h>
    #include <string.h>
    
    
    int main(int argc, char *argv[]){
    
       int add=0;
       int i;
       int sum;
    
       if(argc == 4){
          for(i=1; i<argc; i++){
             if(isdigit(*argv[i]) == 0){
                fprintf(stderr, "%s: found non-numerical arg\n",argv[0]);
                return EXIT_FAILURE;
             } else if(isdigit(*argv[i]) !=0){
                sscanf(argv[i],"%d",&sum);
                add = add +sum;
             } 
          }
          printf("%d\n",add);
       } else{
          fprintf(stderr,"incorrect number of args\n");
       }
       return EXIT_SUCCESS;
    }
    Last edited by Rabbit; Jul 28 '12, 11:35 PM. Reason: Please use code tags when posting code.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Use an or to check for the negative sign when looking at the first character.

    Comment

    • george8000
      New Member
      • Jul 2012
      • 3

      #3
      Omg lol so simple, thanks heaps. I did however have to swap my if statements around aswell because the or statement for the - sign is true in both cases and tends to just output the first if statement

      Comment

      Working...