Salman2013
Salman2013

Reputation: 93

Check the command line arguments for a negative number

I am trying to figure out how to detect the negative numbers in argc (in c).

Code:

int main(int argc, char *argv[]){
    printf("\n");
    for(int i = 0; i < argc; i++){
        printf("%s\n", argv[i]); //print what typed in the command line (arguments)
        //do an if statement here? if less than zero, any help would be great.
    } 
}

I am thinking where I am struggling with the if statement (hopefully I am on track). Any suggestion? Thanks.

The output I am expecting:

$ ./a.out 5 4 6 3 5 -5
5
4
6
3
5
-5
Sorry, you have negative value. 

Then it will quit the program.

Thanks.

Upvotes: 1

Views: 3767

Answers (1)

haccks
haccks

Reputation: 106092

Just add this condition before printf statement in the loop

if(argv[i][0] == '-')
{  
    printf("Sorry, you have negative value. \n");
    exit (0);
} 

Upvotes: 4

Related Questions