trying to use strtol () in c but only works for the first argument

advertisements

I'm just trying to put 4 command line arguments into 4 int. It works for the first argument but returns 0 for the rest I can't seem to see what I'm doing wrong.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
    char* pEnd;
    long li1, li2, li3, li4;
    li1 = strtol(argv[1],&pEnd,10);
    li2 = strtol(pEnd,&pEnd,10);
    li3 = strtol(pEnd,&pEnd,10);
    li4 = strtol(pEnd,NULL,10);

For example, if I run the program as ./a.out -5 5 3 9, then the parsed values are -5 0 0 0.


You give arguments -5 5 3 9. This means that

  • argv[1] contains "-5"
  • argv[2] contains "5"
  • argv[3] contains "3"
  • argv[4] contains "9"

You use

li1 = strtol(argv[1],&pEnd,10);

and now, li1 contains -5 and pEnd holds "", an empty string. The below statements fails and return 0 as strtol couldn't extract numbers from the empty string pEnd

li2 = strtol(pEnd,&pEnd,10);
li3 = strtol(pEnd,&pEnd,10);
li4 = strtol(pEnd,NULL,10);

To fix this problem, you can use

li1 = strtol(argv[1], NULL, 10);
li2 = strtol(argv[2], NULL, 10);
li3 = strtol(argv[3], NULL, 10);
li4 = strtol(argv[4], NULL, 10);

and remove pEnd as it is uneccessary.

An alternative way would be to do what @BLUEPIXY suggested,i.e, wrap the arguments in double quotes so that the whole thing(-5 5 3 9) becomes a single argument and argv[1] holds "-5 5 3 9". When you do this, your code will work as expected.