-1

So basically my problem is that i have the argv array from the stdin an if i type ./a.out 1 i want to convert this 1 into an int or long, the problem is that if i do a cast into a long it converts the number into a random number and if i cast it to an int i get a warning and an error problably.

Program:

#include <stdio.h>

int main(int argc, char* argv[]) {
    int j = (int) argv[1];
    printf("* j = %d\n",j);
    return 0;
}
Martim Correia
  • 483
  • 5
  • 16

1 Answers1

0

try changing it to:

int j = atoi(argv[1]);

you may have to also add to the top:

#include <stdlib.h>

EDIT: To satisfy these kids and their newfangled standard functions. ("validation" this and "undefined behavior" that... in my day, we made due with atoi! And we were lucky to have it!)

char* endPtr;
long j = strtol(argv[1], &endPtr, 10);
printf("j = %ld\n", j);
JoelFan
  • 37,465
  • 35
  • 132
  • 205